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
<malloc.h>
is not defined by the Standard: prefer to use<stdlib.h>
. Also casting the return value frommalloc
(orrealloc
) serves no useful purpose and may hide an error (representation ofvoid*
andint
being different) the compiler would have caught otherwise. – Procession