Attempting to access a null pointer [duplicate]

2019-06-16 21:32发布

问题:

This question already has an answer here:

  • C++ standard: dereferencing NULL pointer to get a reference? 5 answers
  • Why dereferencing a null pointer is undefined behaviour? 12 answers
#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.)