Free a char array that is inside a struct in C

怎甘沉沦 提交于 2019-12-25 05:09:29

问题


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


回答1:


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.




回答2:


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?



来源:https://stackoverflow.com/questions/21495330/free-a-char-array-that-is-inside-a-struct-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!