Search code examples
cfreerealloc

realloc and the ghosts of mallocs past


I know that realloc will free memory when necessary, and I know the third rule of C - "for every malloc there must be an equal and opposite free"... but how do these two work together?

The situation is best described in code:

int main()
{
    myStruct **myStructArray;
    int      i, num_elements;

    num_elements = getnumber(); // gets value for num_elements

    myStructArray = (myStruct **) malloc(num_elements * sizeof(myStruct*));
    for (i=0; i<num_elements; i++)
        myStructArray[i] = (myStruct *) malloc(sizeof(myStruct));

    // so far so good...

    num_elements = getnumber(); // gets new, LOWER value

    myStructArray = realloc(myStructArrary, num_elements * sizeof(myStruct*));

    // rest_of_code, and necessary free loop for myStructArray etc...
}

Obviously the above is nothing more than a snippet, but a snippet paints a thousand words.

Would this create a memory leak? I know the call to realloc will free the pointers' memory, but I can see arguments for and against the possibility that there is still going to be a bunch of memory forgotten about.

A leak can be circumvented by incorporating int number_elements_new into the code and loop free-ing the surplus myStructs before calling realloc to free the (now NULL) pointers.

If realloc does the donkeywork and frees up ALL the associated memory that's great, otherwise I've got to trawl through to make sure nothing has been missed - myStruct itself contains allocated memory and so on.

Thank you for your recommendations...


Solution

  • If you're shrinking the size of your array, you would first need to free each myStructArray[i] where i >= num_elements, otherwise you will have a memory leak.

    Put another way, shrinking the size of the pointer array does not affect the memory that each array element was pointing to.

    Also, in the realloc call, you will want to assign the result to a temporary pointer; if realloc cannot extend or shrink the buffer, it will return NULL, and you'll lose your reference to that block, which will also introduce a leak:

    myStruct **tmp = realloc(myStructArray, ...);
    if (tmp)
    {
      myStructArray = tmp;
      ...
    }