Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 490
qdii Avatar asked Mar 05 '12 22:03

qdii


People also ask

Does realloc automatically free memory?

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.

Can realloc to smaller size fail?

Yes, it can. Thus, if the pool for smaller objects is full, it will fail and return NULL .

Does realloc erase memory?

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.


1 Answers

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."

like image 127
ouah Avatar answered Sep 19 '22 20:09

ouah