user3259860
user3259860

Reputation:

Free a char array that is inside a struct in C

I have a struct that contains an array of strings (char arrays) and an int for the maximum capacity of the array.

typedef struct ArrayList
{
    char **array;
    int capacity;
}

The array is initialized with malloc in its own method.

list->array = malloc(sizeof(char *) * templength);

And the individual strings are initialized as

list->array[nextEmptyString] = malloc(sizeof(str));
strcpy(list->array[nextEmptyString], str);

I need to be able to clear everything about that array from memory and then pass a new pointer to that array, however when I attempt to free the individual strings before freeing the array it scrambles the new array.

for (word = 0; word < list->capacity; word++)
    free(list->array[word]);
free(list->array);
list->array = newArray;

Where list is an ArrayList and newArray is an array of strings. The code runs correctly if I comment out the for loop, but then don't i just have a bunch of orphaned strings floating around in memory?

The intended output is something like Adding Pierre to L1 ... and instead I get Adding �c� to L1 ...

Upvotes: 0

Views: 1574

Answers (2)

sgflt
sgflt

Reputation: 68

You should use strdup function from string.h

list->array[nextEmptyString] = malloc(sizeof(str));
strcpy(list->array[nextEmptyString], str);

seems better as:

list->array[nextEmptyString] = strdup(str);

And the problematic for: Did you initialize a capacity?

Upvotes: 1

Dmitri
Dmitri

Reputation: 9375

When allocating the strings in the array,

malloc(sizeof(str))

only allocates enough space for a char *, rather than the the string it points to (unless str was an ordinary array rather than a pointer). Instead, try

malloc(strlen(str) + 1)

to allocate enough room for the characters in the string plus a terminating null.

Upvotes: 4

Related Questions