-1

I've tried the following code.But it is always crashing. Why? I didn't even change the content of address 0. Compiled on mingw32-g++

#include<iostream>
int main(){
    int* p=0;
    std::cout<<*p;
}
Nya
  • 310
  • 2
  • 10
  • http://stackoverflow.com/questions/2960496/why-is-null-0-an-illegal-memory-location-for-an-object http://stackoverflow.com/questions/2759845/why-is-address-zero-used-for-null-pointer Particularly the second answer of the first question – Karthik T Jan 27 '15 at 02:35
  • `Why?` Because undefined behavior. – user657267 Jan 27 '15 at 02:37
  • "I didn't even change the content of address 0." Reading it is enough to make it undefined behavior. In some cases, this may result in a crash. –  Jan 27 '15 at 02:39
  • I know it's an undefined behavior in terms of c++ standard. And I want to know how compilers do with it generally @remyabel – Nya Jan 27 '15 at 02:43
  • @Nya, eh? Compilers write assembly that dereferences page zero, and then your operating system (assuming you're in userspace on a remotely modern OS) refuses to give it to you, and tells you that with a SIGSEGV. The compiler isn't really making any decision there. – Charles Duffy Jan 27 '15 at 22:01

1 Answers1

2

Dereferencing a null pointer gives undefined behavior.

In a fairly typical case, there's really nothing there. For example, on an x86 in protected mode, you typically set up some page table entries for the beginning of memory that say nothing is present there, so any attempt at reading or writing that address will result in a page fault (e.g., both Windows and Linux do this).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111