gpt4 book ai didi

c - 在 clang 中使用 realloc 来缩小内存

转载 作者:太空狗 更新时间:2023-10-29 15:36:49 25 4
gpt4 key购买 nike

我在涉及 realloc 的 clang 下遇到了我们的代码问题。此代码在 gcc 和 visual studio 下运行良好,因此我有兴趣了解 clang 的行为。我们的代码做了类似的事情(省略了错误处理等):

// allocate way more memory than we need
char * memory = malloc(500000);
int memoryused = 0;

// ... code goes here that fills up the memory, keeping track by
// setting memoryused ...

// now we're done, shrink the memory down to the size it needs
memory = realloc(memory, memoryused);

在 gcc 和多个版本的 MSVC 下,内存指针没有移动。但是,在 clang 下,它似乎移动了内存,即使所需的大小仅为 1-2000 字节。

clang 这样做有什么特别的原因吗?我唯一能想到的是,也许它为大型和小型分配或其他东西保留单独的堆。否则,移动内存似乎有点低效,因为它可以截断旧内存块并继续使用它而根本不必复制数据。

最佳答案

我也曾经想过这样的事情:Is realloc guaranteed to be in-place when the buffer is shrinking?

总结响应 - realloc 允许移动缓冲区,即使它只是缩小......具体细节取决于您的特定库实现。

来自 c99(强调我的):

The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object), or a null pointer if the new object could not be allocated.

正如您所猜测的(以及根据链接问题中的一些回答)一些 分配器显然会对堆进行分区,因此特定大小范围的分配来自同一个分配桶 -在许多小对象可能散落的情况下防止堆碎片,这将阻止分配大的连续 block 。

希望这对您有所帮助。

关于c - 在 clang 中使用 realloc 来缩小内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7480620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com