Search code examples
cmemory-leaksfreerealloc

Should I use "free" on 2D array when I used realloc?


I have 2D array declared like this:

int **array= NULL;

and then, somewhere in code I add elements like this:

int* tempArray1D = FuncThatReturnsIntStarArray();
array= (int**)realloc(array, (arraySize+ 1) * sizeof(int*));
*(array+size - 1) = tempArray1D;

If I want to delete one (last) element from 2D array, should I use free() and realloc on 1D array (int*) or realloac take care of all that. For example:

free(*(array+ size- 1));
array= (int**)realloc(array, (size- 1) * sizeof(int*));

or just:

array= (int**)realloc(array, (size- 1) * sizeof(int*));

Example with free() cause some issues and im not sure if that way of avoiding memory leaks is correct and I have somewhere else in the code other bug, or it is just bad way of doing that.


Solution

  • realloc() has no knowledge about the things you store in the space. You need to take care of them yourself.

    If FuncThatReturnsIntStarArray() allocates the memory whose address it returns, and if you have no other mechanism (like a function FuncThatFreesAllocatedArray()), you should free that memory.

    (BTW, FuncThatReturnsIntStarArray() is a bit misleading, because is does not return an array of int "stars" (vulgo: pointers). Something like FuncThatReturnsPointerToInts() is more appropriate.)