Attempting to access a null pointer [duplicate]

▼魔方 西西 提交于 2020-01-03 08:35:11

问题


#include <iostream>

int main()
{
    int* i = 0;
    int x = (*i);
    std::cout << x;
}

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.

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

If it is defined, what does C++ guarantee me when I try and access a null pointer?


回答1:


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.




回答2:


What makes your process crash here is the OS stopping your program from fiddling with memory it does not have access to (at address 0). Windows will give you an "Access violation", Linux/Unix will give you a "segmentation fault".

Also, see Why are NULL pointers defined differently in C and C++? for a quote of what a null pointer is in the standard




回答3:


It is not defined in C++ so it may not crash on some operating systems, but you can count on a crash under current (and previous) versions of Windows and Linux because neither of those will let you (as a user process) access that memory location.

Also, under Windows, if you want to cause a program break, try DebugBreak(); which causes an exception (MSDN says: Causes a breakpoint exception to occur in the current process. This allows the calling thread to signal the debugger to handle the exception.)



来源:https://stackoverflow.com/questions/17061203/attempting-to-access-a-null-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!