Rio
Rio

Reputation: 14882

realloc memory in string array in C

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.

Upvotes: 3

Views: 793

Answers (2)

Potatoswatter
Potatoswatter

Reputation: 137790

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.

Upvotes: 2

MByD
MByD

Reputation: 137312

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).

Upvotes: 4

Related Questions