I have to safely free an array: char** a; It’s like a string list. I know how many char* I have in it. But I have trouble to release ALL the memory. Is there like a function that I can use like to free 20 bytes ? I tried:
for (int i = 0; i < length; i++)
if (a[i] != null)
free(a[i]); // some of a[i] ARE null, non-null have different sizes
free(a); // crashes here
but I get runtime errors with asm debugging.
Every thing in a has been malloced. For a I malloced 5 strings (each pointer 4 bytes) -> 20 bytes. How can I free the whole char** ?
You can’t free 20 bytes unless you allocated 20 bytes. You can only free a block. The size of that block is specified at allocation time. For each block allocated, you need a separate de-allocation.
You can try to change the size of a block by using
reallocbut that’s not deleting an arbitrary part of that block.If both the array and the indicvidual items in the array have been allocated using
malloc, then your approach is correct. Free each of the elements, then free the array: