gpt4 book ai didi

c - 缩小指针持有的内存时的重新分配行为

转载 作者:行者123 更新时间:2023-12-02 07:08:48 25 4
gpt4 key购买 nike

困惑1:
man realloc 表示如果必须进行新的分配以将对象的大小调整为新的大小,则该对象将被移动。但是裁员的时候很多地方都写着it is possible to move data in memory to a new place (所以)。这在我脑海中造成了困惑。我们如何发现裁员是否会导致新的分配,因为在手册页和 gnu page 中没有明确提及裁员案例。 .

困惑2:
此外,当我们执行以下操作时:

void * ptr1 = malloc(SOMEBIGSIZE);
void * ptr2 = realloc(ptr1, SOMESMALLSIZE);

评估 ptr1==ptr2 结果为真。这意味着 ptr2 指向相同的 ptr1。那么,2.1 和 2.2 哪个是正确的?
(2.1) ptr1 没有缩小尺寸,如果 SOMEBIGSIZE>>>SOMESMALLSIZE 可能会很糟糕,我们在内存方面没有任何优势。
(2.2) 如果 ptr1 被收缩,那么 ptr1+SOMESMALLSIZE 到 ptr1+SOMEHUGESIZE 地址范围内的内存会发生什么变化?它是已释放还是标记为已释放?

最佳答案

C 标准从用户程序的角度讲了realloc 的行为。它没有定义实现。

以下是实现标准强加的相关要求(在您的 Q 中询问)。

C99 标准 7.20.3.4-1:realloc 函数:

The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.

C99 标准 7.20.3.4-4:

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.

关于c - 缩小指针持有的内存时的重新分配行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8084459/

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