Shrinking with realloc

拈花ヽ惹草 提交于 2019-12-01 16:13:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/3788966/shrinking-with-realloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!