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
If realloc succeeds, it will take ownership of the incoming memory (either manipulating it or free ing it) and return a pointer that can be used ("owned") by the calling function. If realloc fails (returns NULL ), your function retains ownership of the original memory and should free it when it's done with it.
Yes, it can. Thus, if the pool for smaller objects is full, it will fail and return NULL .
Will I lose my data? No, the data will be copied for you into the new block that the returned p points at, before the old block is freed. This all happens before realloc returns, so the new p points to your data still.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With