c - 为什么在尝试打印空指针时出现错误

标签 c pointers

#include <stdio.h>
void main ()
{
    int* p = NULL;
    printf("%d", *p);
}

它打印:

Exception thrown: read access violation.
p was nullptr.

最佳答案

NULL 指针不能被取消引用。

这样做会调用 undefined behavior ,在这种情况下表现为您的程序崩溃。

这记录在 C standard 的第 6.5.3.2p4 节中:

4 The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type "pointer to type", the result has type "type". If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined. 102)

102) Thus, &*E is equivalent to E (even if E is a null pointer), and &(E1[E2]) to ((E1)+(E2)). It is always true that if E is a function designator or an lvalue that is a valid operand of the unary & operator, *&E is a function designator or an lvalue equal to E. If *P is an lvalue and T is the name of an object pointer type, *(T)P is an lvalue that has a type compatible with that to which T points.

Among the invalid values for dereferencing a pointer by the unary * operator are a null pointer, an address inappropriately aligned for the type of object pointed to, and the address of an object after the end of its lifetime.

如果你想打印指针本身,将它传递给 printf 而不取消引用它并使用 %p 格式说明符:

printf("%p\n", (void *)p);

关于c - 为什么在尝试打印空指针时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55123976/

相关文章:

c - strace 在不同缓冲区上的 Linux write 系统调用有不同的结果

c - XCreateGC() 中的 (value)mask 真的有必要吗?

c++ - 在 C++ 中返回仿函数的正确方法

c - 为什么我的 C 程序在这里打印 0.000000?

c++ - 禁用优化时没有 "may be used uninitialized"

c++ - 在指向 C++ 中的缓冲区(字符串 "")的空指针上使用 sizeof() 以获得 BYTES 的大小?

c - C 中的 2 D 字符数组,其中每个值都是 C 字符串

c++ - 我可以检查 C++ 迭代器是否为 null 吗?

c - 初始化使指针无需强制转换

c struct 通过偏移量获取数据