c - 在 C 中获取未定义或实现定义行为的无效指针的值?

标签 c pointers undefined-behavior invalid-pointer

根据 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 by ptr 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/

相关文章:

c - 此代码如何计算经过的 CPU 周期数?

c - 从文件读取时的制表符宽度

c++ - C++ 中指向整数映射和查找的高效指针

c++ - 不同数据类型的sizeof(datatype pointer)/sizeof(data type)取值不同,为什么?

c++ - 为什么这些示例中的一个是未定义行为而另一个不是?

c++ - 使用 C++11,写 f(x++)、g(x++) 是未定义的行为吗?

计算 "based"数据校验和。 (SHA1/2 等)

c++ - 我需要一些 C++ 结构建议

c++ - 当 extern 声明和定义之间存在不匹配的类型时会出现什么行为?

c - 在 C 中使用指针交换列