gpt4 book ai didi

c - 在 C 中是否可以在不移动它的情况下缩小分配的内存?

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

是否有一种方法/函数可以释放内存而不可能将其移动到 c 中的新指针?

谢谢!

最佳答案

根据 C99 标准的严格解释,对 realloc() 的任何调用,包括减少已分配 block 的大小,都可能返回与参数不同的指针。事实上,根据标准的严格解释,您不允许将旧指针与新指针进行比较,因为将旧指针传递给 realloc() 会使它的所有现有副本变得不确定。

The realloc function deallocates the old object pointed to by ptr and returns apointer to a new object that has the size specified by size. … (C99 7.20.3.4:2)


但是,我系统上 realloc() 的手册页说:

If there is not enough room toenlarge the memory allocation pointed to by ptr, realloc() creates a newallocation, copies as much of the old data pointed to by ptr as will fitto the new allocation, frees the old allocation, and returns a pointer tothe allocated memory.

这或多或少意味着 realloc() 只能在用于扩大块时移动数据并返回新指针。这表明,在此平台上,realloc() 可用于减小从 malloc() 获得的 block 的大小,而不会有移动它的风险。

如果我要使用 realloc() 来减少分配 block 的大小而不移动它,我会使用下面的检查:

uintptr_t save = old;
void * new = realloc(old, …);
assert (save == (uintptr_t) new);

这些预防措施并非毫无意义,例如参见 this informal undefined behavior competition 中的获胜者 #2| .

2021 编辑:然而,多年后,进一步努力将 C 的定义重新解释和发展为高级语言的定义,这意味着即使上述三行中的任何一行都是完全合法的,即使在执行它们之后,您也不能使用 old 的旧副本访问 new 指向的 block ,即使这些指针指向同一个地方。参见 the current paper about pointer provenance in C .

关于c - 在 C 中是否可以在不移动它的情况下缩小分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18171151/

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