使用 realloc 进行收缩

发布于 2024-09-24 23:32:33 字数 323 浏览 0 评论 0原文

我在这个问题中遇到了这一小段代码,&想知道,

当指向的内存空间缩小时,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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

弥繁 2024-10-01 23:32:33

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文