I m trying to free the memory space for an array of char:
static void cleanArray(char* array)
{
int i;
int size = strlen(array) + 1;
for(i = 0; i < size; i++)
free(array[i]);
free(array);
}
int main(){
char* array = (char *)malloc(1 * sizeof(char*));
int c;
for(c=0;c<100;c++){ //code to populate some string values in the array.
void *p = realloc(array, (strlen(array)+strlen(message)+1)*sizeof(char*));
array = p;
strcat(array, "some string");
}
cleanArray(array); //I get error only when I call this method.
}
But for the above code I m getting Segmentation fault
error.
And when I just try the following code instead of cleanArray() I dont think the array is freed up:
free(array);
printf("%s",array); //it prints all the values in the array. Hence, I concluded it is not freedup.
Line free(array[i]);
in loop have problem. array[i]
is a char value(which is actually int by integer promotion) and passing that value to free
will be considered as pointer. Now you are trying to free that address about which you do not have any idea.
There are multiple problems:
free()
on each character of the string. Just call free(array)
. sizeof(char*)
in malloc()
and realloc()
is incorrect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.