Shrinking with realloc
Asked Answered
R

1

6

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?

Reborn answered 24/9, 2010 at 16:14 Comment(0)
M
12

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.

Mordecai answered 24/9, 2010 at 16:19 Comment(1)
Just to remove any doubt, I've actually encountered this situation on iOS 6 where a realloc of 40K down to 224 bytes actually moves the memory to a new location.Dyslogistic

© 2022 - 2024 — McMap. All rights reserved.