I encountered this small piece of code in this question, & wanted to know,
Can the realloc()
function ever move a memory block to another location, when the memory space pointed to is shrinked?
int * a = malloc( 10*sizeof(int) );
int * b = realloc( a, 5*sizeof(int) );
If possible, under what conditions, can I expect b
to have an address different from that in a
?
It's possible for realloc
to move memory on any call. True in many implementations a shrink would just result in the change of the reserved size in the heap and wouldn't move memory. However in a heap which optimized for low fragmentation it may choose to move the memory around to a better fitting location.
Don't depend on realloc
keeping memory in the same place for any operation.