When I realloc a buffer to be smaller, does it delete the data in the buffer until it reach the correct size?

584 views Asked by At

My question is a little confusing, but what I'm asking is what does realloc do with the left over data when it minimizes it buffer? For example, lets just say I had a buffer filled with 50-bytes (assuming my buffer can hold up to 50-bytes of data). Later on in my code I resize my buffer with realloc to now only hold up to 30-bytes. What does realloc do with the left over 20-bytes?

1

There are 1 answers

1
Cubbi On BEST ANSWER

realloc is exactly malloc+memcpy+free, except that sometimes it manages to do it in-place and the pointer it returns is numerically equal to the pointer you put in (but you can never rely on that). The left-over 20 bytes are freed.

From the C standard, 7.22.3.5 The realloc function

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. The contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.

see also http://en.cppreference.com/w/c/memory/realloc or http://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html