I tested the following code in gcc 4.8.3 and msvc v120.
#include <iostream>
using std::cout;
void bar(int &x)
{
cout << "bar\n";
int y = x; // Crash here...
}
void foo(int *x)
{
cout << "foo\n";
bar(*x); // No crash here...
}
int main()
{
foo(0);
return 0;
}
output:
$ ./test
foo
bar
Segmentation fault (core dumped)
I expected that it would crash upon the *x
, however it crashes when the int reference is dereferenced. It was compiled with the following g++ -O0 -std=c++11 -pedantic -o test test.cpp
. Does anyone have an explanation for this behaviour? How is the reference initialized without dereferencing the null pointer?