-1

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?

user2864740
  • 60,010
  • 15
  • 145
  • 220
Seamus Connor
  • 1,765
  • 1
  • 18
  • 24
  • 3
    Because undefined behavior is just that -- undefined. – Fred Larson Jun 16 '14 at 18:55
  • 1
    Undefined behaviour can do whatever it darn well pleases. – ghostofstandardspast Jun 16 '14 at 18:55
  • 1
    Have you run `g++` with `-S` to see what assembly the compiler is generating? What the other commenters are saying about undefined behaviour is technically correct but from a practical perspective, a reference is going to be implemented as a pointer. You can initialize a pointer to NULL without crashing. It's the dereference that causes the crash. And you are confusing initialization (`bar(*x)`, which is practically equivalent to `bar((int *)0)`) with dereferencing (`int y = x`, which is equivalent to `int y = *((int *)0)`). – 0xbe5077ed Jun 16 '14 at 18:55
  • 1
    Since dereferencing a `nullptr` is UB, it's simply not defined where it will crash, or if it will at all. Your fridge might explode, that's what's the nature of _'Undefined Behavior'_! – πάντα ῥεῖ Jun 16 '14 at 18:55
  • 1
    Setting adide the entire notion of undefined behaviour, why do you think there should be a segfault there? Which memory access should trigger it? – n. m. could be an AI Jun 16 '14 at 19:00
  • Dereferencing NULL is undefined in general, but is very strongly defined for specific platforms. For example, x86-64/Linux when configured in a standard configuration does not allow 0 in a processes VM, and will therefore segfault when NULL is dereferenced. – Seamus Connor Jun 16 '14 at 19:09
  • 1
    @Seamus: You're referring to dereferencing at the machine code level. That is, reading or writing to an invalid memory location. In C++ terms, dereferencing does not necessarily result in a memory read or write. For example, when storing the result of a dereferenced pointer in a reference, there is no need to look at the location which the pointer points at. In your case, a read of that location doesn't happen until `int y = x;` – Benjamin Lindley Jun 16 '14 at 19:28

1 Answers1

0

In case of undefined behavior nothing can be predicted. Anything could happen. The program may run as per your expectation or it may erase your hard disk!!

haccks
  • 104,019
  • 25
  • 176
  • 264