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

标签 c macos osx-lion clang realloc

我在涉及 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/

相关文章:

ruby-on-rails - 如何删除 XCode 4.2 并安装 4.1 以在 OSX Lion 上开发 Ruby/Rails?

macos - 在与要安装的软件包具有相同 root 权限的软件包中创建安装程序插件 (Mac OS X)

c - 成员 "Token"的 Yacc 错误请求不是结构或 union

c - "bus error"带有(非常)简单的 opencv 程序(使用 Mac Os X)

delphi - Gethomepath 不适用于 iOS 5/OSxLion

Python写入数据库时​​总线报错问题

swift - 核心 WLAN MCS 索引?

python - 为什么 Python 扩展模块需要在 Windows 上用 MSVC 编译?

c - C 中的二维数组排序

c - strcat 不影响全局字符串