3

I'm trying to satisfy valgrind and come up with a nice implementation, but I'm coming across a snag. Essentially what I'm trying to do is reduce two strings in an array to one. Let's say arr contains

{ "One", "Two", "Three" }

And that the memory allocation for each string has been done as it should be (a la arr[1] = malloc(strlen("one") + 1) and strcpy(arr[1], "One").

I do some string manipulation and try to do:

strcpy(arr[1],"OneTwo");

and remove arr[2] but this is inherently problematic because the memory allocation for arr[1] has changed. Something tells me that doing malloc again would be bad.

I could do realloc but that would require either freeing arr[2] and shifting everything after it down one space and realloc'ing. I could also do arr[2] = NULL but valgrind disagrees.

Any hints would be greatly appreciated.

2
  • 4
    "I'm trying to satisfy valgrind " - erm no, you are trying to write code that isn't flawed with memory overwrite errors! Commented Apr 10, 2011 at 1:28
  • First you should give us the complete declaration. The snipset makes a whole lot of difference if you have char arr[n][m], char *arr[] or char const*arr[]. Commented Apr 10, 2011 at 13:33

2 Answers 2

4

reallocate arr[1] and append arr[2] to the end of the string, then free arr[2] (and set arr[2] = NULL to avoid confusion later).

Sign up to request clarification or add additional context in comments.

Comments

2

Why would reallocing arr[1] require any modification of anything else?

strcpy( arr[1] = realloc( arr[1], sizeof "OneTwo" ), "OneTwo" );
free( arr[2] );
arr[2] = NULL;

Looks good to me. There's nothing after arr[2] here so no shifting to do. If there were, then yes, removing from the middle of any array demands that you shift down the following elements.

7 Comments

doesn't that assume that arr[1] (arr[i]) was malloc'ed? i.e. can the compiler layout { "One", "Two", "Three" } as non-malloc'ed memory?
@Mitch: He specifically said that the strings were malloced in the first place. It's not clear from his description using literals, true.
@Potatoswatter: ah yes, so he did, but I wondered if this is obvious to the poster. There's allocated and malloced!
This assumes that realloc succeeds. Fine for demonstration, but not so good in production.
@dmckee: In principle yes, but on my platform at least (OS X) the system would rather SIGSTOP your process and present a dialog asking the user to free up memory, than allow malloc to fail.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.