I need your advice on this piece of code:
the table fields options[0], options[1] etc… doesn’t seem to be freed correctly.
Thanks for your answers
int main()
{
....
char **options;
options = generate_fields(user_input);
for(i = 0; i < sizeof(options) / sizeof(options[0]); i++) {
free(options[i]);
options[i] = NULL;
}
free(options);
}
char ** generate_fields(char *)
{
char ** options = malloc(256*sizeof(char *));
...
return options;
}
The problem is this:
optionsis a pointer type, not an array type, sosizeof(options)will always be the same (typically 4 bytes on a 32-bit machine or 8 bytes on a 64-bit machine), sosizeof(options)/sizeof(options[0])will almost always be 1.The key is to always
freememory in the same manner as youmalloc‘ed it. So, if youmalloca 2-dimensional array and thenmalloca series of 1-dimensional arrays, you need to do the reverse when freeing it:Note that if the size (256 in this case) is not a constant, you need to keep track of it yourself, since otherwise you have no way of knowing how many times to loop when freeing.