Search code examples
csizeofrealloc

Reallocating less memory than initially for a pointer in C


If I try to use realloc to allocate less memory for a pointer than it initially had allocated, will the redundant memory be freed or will the reallocation result in a memory leak?

I don't know how I could test this, sizeof seems to return the same value independent of how many re-allocations I do.


Solution

  • The definition of a memory leak is: memory you can no longer free since you lost all pointers ("handles") to it. Since realloc() returns a pointer to the possibly moved location, it doesn't create a leak in this sense. Whether the excess memory after shrinking is available for further allocations is an implementation detail of your particular library.

    Note however that you can in fact easily create a memory leak with realloc if you don't use a temporary variable:

    m = realloc (m, size);  /* Potential memory leak. */
    

    If realloc returns NULL, you've lost the previous value of m (okay, we're out of memory, so a memory leak is just another problem now, but still). I recommend to get into the habit of writing

     t = realloc (m, size);
     if (t != NULL)
        m = t;
     else
        deal_with_out_of_memory_situation ();
    

    Note that sizeof never yields the size of allocated memory, but always the size of the object (which for pointers to allocated memory is the size of the pointer, not the size of pointed to memory.)