Search code examples
cmallocfreerealloc

Can I assume that calling realloc with a smaller size will free the remainder?


Let’s consider this very short snippet of code:

#include <stdlib.h>

int main()
{
    char* a = malloc(20000);
    char* b = realloc(a, 5);

    free(b);
    return 0;
}

After reading the man page for realloc, I was not entirely sure that the second line would cause the 19995 extra bytes to be freed. To quote the man page: The realloc() function changes the size of the memory block pointed to by ptr to size bytes., but from that definition, can I be sure the rest will be freed?

I mean, the block pointed by b certainly contains 5 free bytes, so would it be enough for a lazy complying allocator to just not do anything for the realloc line?

Note: The allocator I use seems to free the 19 995 extra bytes, as shown by valgrind when commenting out the free(b) line :

==4457== HEAP SUMMARY:
==4457==     in use at exit: 5 bytes in 1 blocks
==4457==   total heap usage: 2 allocs, 1 frees, 20,005 bytes allocated

Solution

  • Yes, guaranteed by the C Standard if the new object can be allocated.

    (C99, 7.20.3.4p2) "The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size."