根据 this,获取无效指针的值是 C++ 中实现定义的行为.现在考虑以下 C 程序:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int* p=(int*)malloc(sizeof(int));
*p=3;
printf("%d\n",*p);
printf("%p\n",(void*)p);
free(p);
printf("%p\n",(void*)p); // Is this undefined or implementation defined in behaviour C?
}
但是 C 中的行为也一样吗?上述 C 程序的行为是未定义的还是已定义的? C99/C11 标准对此有何规定? 请告诉我 C99 和 C11 中的行为是否不同。
最佳答案
扩展 Andrew Henle 的回答:
来自 C99 标准 6.2.4:
An object has a storage duration that determines its lifetime. There are three storage durations: static, automatic, and allocated. Allocated storage is described in 7.20.3. […] The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
然后在 7.20.3.2 中:该标准继续描述 malloc()
、calloc()
和 free()
,并提到
The
free
function causes the space pointed to byptr
to be deallocated.
在 3.17.2 中:
indeterminate value
either an unspecified value or a trap representation
在 6.2.6.1.5 中:
Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. […] Such a representation is called a trap representation.
由于指针变得不确定,并且不确定值可以是陷阱表示,并且您有一个左值变量,并且读取左值陷阱表示是未定义的,因此是的,行为可能是未定义的。
关于c - 在 C 中获取未定义或实现定义行为的无效指针的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33584843/