Search code examples
c++crealloc

Also check realloc() if shrinking allocated size of memory?


When you call realloc() you should check whether the function failed before assigning the returned pointer to the pointer passed as a parameter to the function...

I've always followed this rule.

Now is it necessary to follow this rule when you know for sure the memory will be truncated and not increased?

I've never ever seen it fail. Just wondered if I could save a couple instructions.


Solution

  • realloc may, at its discretion, copy the block to a new address regardless of whether the new size is larger or smaller. This may be necessary if the malloc implementation requires a new allocation to "shrink" a memory block (e.g. if the new size requires placing the memory block in a different allocation pool). This is noted in the glibc documentation:

    In several allocation implementations, making a block smaller sometimes necessitates copying it, so it can fail if no other space is available.

    Therefore, you must always check the result of realloc, even when shrinking. It is possible that realloc has failed to shrink the block because it cannot simultaneously allocate a new, smaller block.