#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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With