尝试访问空指针 [英] Attempting to access a null pointer
问题描述
#include <iostream>
int main()
{
int* i = 0;
int x = (*i);
std::cout << x;
}
当我使用Visual Studio 2010
编译并运行上述程序时,该程序将崩溃,并且我知道它会崩溃,因为我将指针设置为0.
The above program will crash when I compile and run it using Visual Studio 2010
and I know it crashes because I set the pointer to 0.
我想知道的是,使用标准中定义的C ++访问null pointer
还是未定义,我只是很幸运,由于我的编译器/计算机/操作系统,我的程序崩溃了
What I would like to know, is accessing a null pointer
in C++ defined in the standard or is it undefined and I just happen to get lucky that my program crashed because of my compiler/computer/operating system
如果已定义,当我尝试访问空指针时,C ++可以保证我什么?
If it is defined, what does C++ guarantee me when I try and access a null pointer?
推荐答案
取消引用空指针将调用未定义的行为.它可能在不同的编译器上产生不同的结果,甚至更多-如果多次编译,同一编译器上可能会发生不同的事情.完全不能保证行为.
Dereferencing a null pointer will invoke undefined behavior. It may result in different things on different compilers, even more - different things may happen on the same compiler if compiled multiple times. There are no guarantees of the behavior at all.
这篇关于尝试访问空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!