gpt4 book ai didi

c - 是否允许编译器回收释放的指针变量?

转载 作者:太空狗 更新时间:2023-10-29 16:35:50 27 4
gpt4 key购买 nike

据说

a compiler is free to reuse the pointer variable for some other purpose after the realloc being freed, so you have no guarantee that it has the same value as it did before

void *p = malloc(42);
uintptr_t address = (uintptr_t)p;
free(p);

// [...] stuff unrelated to p or address

assert((uintptr_t)p == address);

可能会失败。

C11附件J.2读

The value of a pointer that refers to space deallocated by a call to the free or realloc function is used (7.22.3) [is undefined]

但是附件当然不是规范的。

附件 L.3(规范性但可选)告诉我们如果

The value of a pointer that refers to space deallocated by a call to the free or realloc function is used (7.22.3).

结果允许是关键的未定义行为。

这证实了声明,但我希望看到标准本身而不是附件中的适当引用。

最佳答案

当一个对象到达其生命周期的尽头时,所有指向它的指针都变得不确定。这同样适用于 block 作用域变量和分配的内存。适用条款为C11中的6.2.4:2。

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime. If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

将不确定内存用于任何事情,包括明显无害的比较或算术,是未定义的行为(在 C90 中;后来的标准使问题变得非常复杂,但编译器继续将不确定内存的使用视为未定义行为)。

例如,下面的程序打印pq 既不同又相同如何?显示了各种编译器的执行结果 here .

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main(int argc, char *argv[]) {
char *p, *q;
uintptr_t pv, qv;
{
char a = 3;
p = &a;
pv = (uintptr_t)p;
}
{
char b = 4;
q = &b;
qv = (uintptr_t)q;
}
printf("Roses are red,\nViolets are blue,\n");
if (p == q)
printf ("This poem is lame,\nIt doesn't even rhyme.\n");
else {
printf("%p is different from %p\n", (void*)p, (void*)q);
printf("%"PRIxPTR" is not the same as %"PRIxPTR"\n", pv, qv);
}
}

关于c - 是否允许编译器回收释放的指针变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26073842/

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