使用 realloc 进行收缩
我在这个问题中遇到了这一小段代码,&想知道,
当指向的内存空间缩小时,realloc()
函数是否可以将内存块移动到另一个位置?
int * a = malloc( 10*sizeof(int) );
int * b = realloc( a, 5*sizeof(int) );
如果可能,在什么条件下,我可以期望 b
的地址与 a
中的地址不同?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
realloc
可以在任何调用中移动内存。确实,在许多实现中,收缩只会导致堆中保留大小的更改,而不会移动内存。然而,在针对低碎片进行优化的堆中,它可能会选择将内存移动到更合适的位置。不要依赖
realloc
将内存保留在同一位置以进行任何操作。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.