Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempting to access a null pointer [duplicate]

Tags:

c++

null

pointers

#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?

like image 744
Caesar Avatar asked Jun 12 '13 08:06

Caesar


2 Answers

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.

like image 146
Ivaylo Strandjev Avatar answered Sep 29 '22 22:09

Ivaylo Strandjev


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

like image 31
rectummelancolique Avatar answered Sep 29 '22 21:09

rectummelancolique