Alex Rivera | Logout

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

Asked 2012-03-05T22:36:53.140
44

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
Edit
Report

1 Answer

2

It seems unlikely that 19995 bytes were freed. What's more likely is that realloc replaced the 20000-byte block by another 5-byte block, that is, the 20000-byte block was freed and a new 5-byte block was allocated.

answered 2012-03-05T22:54:04.063

Your Answer