gpt4 book ai didi

c - 在 C99 中使用 free() 之后的指针?

转载 作者:行者123 更新时间:2023-12-04 12:27:32 25 4
gpt4 key购买 nike

我的教授展示了以下代码:

void *p1=malloc(1024);
free(p1);
void *p2=malloc(1024);
if (p1==p2)
{
printf("Now What?")
}
他说这是不安全的,但为什么呢?
我知道我们不应该尝试访问已释放的内存。然而,知道指针指向哪里是可以的,因为它只是一个普通的指针,只要我们不尝试从它指向的地方读取。

最佳答案

这实际上是不安全的,因为指向已释放内存的指针是不确定的。
C standard的附件J.2 ,其中给出了 undefined behavior 的示例,包括以下内容:

  • The value of a pointer to an object whose lifetime has ended is used (6.2.4).

...

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

其中关于内存管理功能的第 7.22.3p1 节指出:

... The lifetime of an allocated object extends from the allocationuntil the deallocation ...


定义对象生命周期的第 6.2.4p2 节指出:

The lifetime of an object is the portion of programexecution during which storage is guaranteed to be reservedfor it. An object exists, has a constant address, and retainsits last-stored value throughout its lifetime. If an object isreferred to outside of its lifetime, the behavior is undefined.The value of a pointer becomes indeterminate when the object it pointsto (or just past) reaches the end of its lifetime.

关于c - 在 C99 中使用 free() 之后的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69486161/

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