查找分配是否可以微不足道地调整大小?

Find if allocation is trivially resizable?

realloc 可能只是在这里和那里更新簿记信息以增加您的分配大小,或者它实际上可能 malloc 一个新的和 memcpy 以前的分配(或者可能失败) .

如果分配可微调大小,我希望能够查询内存管理器(要么是因为它保留的比我mallocd 多,要么是因为它能够coalesce adjacent blocks 等...),如果是,那么我会要求它继续这样做,否则我想要 mallocmemcpy 原始分配的任意子集我自己按任意顺序。

其他 Whosebug 答案似乎是以下四种之一:

注意:这个问题发布在 C 和 C++ 标签下,因为来自任何一种语言的解决方案都是可以接受的和相关的。

编辑 1:

用FB向量的话来说:

But wait, there's more. Many memory allocators do not support in- place reallocation, although most of them could. This comes from the now notorious design of realloc() to opaquely perform either in-place reallocation or an allocate-memcpy-deallocate cycle. Such lack of control subsequently forced all clib-based allocator designs to avoid in-place reallocation, and that includes C++'s new and std::allocator. This is a major loss of efficiency because an in-place reallocation, being very cheap, may mean a much less aggressive growth strategy. In turn that means less slack memory and faster reallocations.

this

我想您想要得到的是 malloc 内存块后的备用 space 大小。有可能,内存管理器在每个块之前预留了一个块头,你可以从块头中获取你想要的信息,但显然它是不可移植的,因为各种内存管理器的实现不同。 我认为更好的方法是使用内存池自己管理堆内存,这样会更高效和可移植。

标准内存接口有很好的文档记录。如果您想要某些不属于该界面的功能,您的解决方案将是自定义的、第三方的或特定于平台的。

  • Suggest it's impossible. C already assumes the presence of a memory manager with ability to either resize allocations in place or create a new one. So, why can't I have one more level of control on it?

因为它不是标准界面的一部分。它可以成为标准接口的一部分并不意味着它标准接口的一部分。

... We can have aligned malloc; why not this ?

如果您希望它出现在标准中,请向工作组提出更改建议。它不会很快到达。

如果你想让某些东西现在工作,你需要编写自己的分配器或找到满足你要求的第三方分配器。

注意

  • Suggest a platform specific extension. This is not practical, as my code, like a lot of C code, requires portability.

这不是一个真正的问题(或者至少,人们经常可以很好地应对)。您可能必须为要支持的每个平台编写不同的实现(并在没有更好可用的情况下退回到 realloc),但这对于跨平台代码来说并不少见。

Suggest realloc anyways. This can be quite inefficient for large quantities of data, where the double-copy can have serious effect.

由于为什么 realloc有时可以避免复制和分配的原因,这是无关紧要的一点,因为在实际实现中,大量数据不存在这种情况。如果您知道分配很大,那么可以相当安全地假设 realloc 必须进行复制和分配。因此,您无需进行“不可能”检查即可做出选择。

如果重新分配是可选的,而您负担不起副本,则无条件选择不重新分配的选项。如果重新分配不是可选的,那么 realloc 是否复制和分配都不会影响您必须执行的操作。

Suggest a platform specific extension. This is not practical, as my code, like a lot of C code, requires portability.

这是实现您要求的唯一方法,因为没有标准方法来查询 realloc 是否会复制和分配。

但是,请记住,可以通过使用预定义的宏有条件地禁用此功能来移植此类代码。

Suggest it's impossible.

如果您选择依赖标准 C++,这是正确的。

is there a way to do this that I have not come across in my search ?

不,列表很详尽。