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.