-2

I am trying to run the following program :

#include <iostream>
struct Foo {
    int x;
    void bar() {
        std::cout << "La la la" << std::endl;
    }
    void baz() {
        std::cout << x << std::endl;
    }
};
int main() {
    Foo *foo = NULL;
    foo->bar();
    foo->baz();
}

Output :

./a.out 
La la la
Segmentation fault (core dumped)

I am using g++ version 7.3.0 on ubuntu 18.04. Shouldn't both the calls fail as the object has been set to null?

Abhishek Jha
  • 61
  • 1
  • 1
  • 8
  • 5
    Dereferencing a null pointer leads to [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior). It might seem to work, it might crash, or it might give you [nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html). Anyway, once you have undefined behavior, any attempt of explaining the behavior is moot. – Some programmer dude Jun 07 '18 at 07:14

3 Answers3

3

There is no use in wondering how and when undefined behaviour works. Technically, in the second case, you access a member variable of the object (which is NULL) and which you don't in the first call, so this might be the reason for the crash.

Jodocus
  • 7,493
  • 1
  • 29
  • 45
2

The behaviour of your code is undefined, you cannot dereference a pointer set to NULL. If you want to know what a compiler has done with your code, then check the generated assembly.

Interestingly many compilers will allow you to reach a static member function in this way (and will say so in their documentation); as that was the workaround used by programmers in CFront (the forerunner to C++) before static member functions were formally introduced in C++89. Note that bar is essentially a static function as it does not access any class member data or call any class member functions.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

as said this code is undefined behavior meaning it isn't predictable and shouldn't been relied on

in this spécifique case one of your fonction access a data membre meaning this(witch is NULL) pointer need to be dereferenced and in the other case the this pointer doesn't need to be dereference because nothing from the class was accessed

Tyker
  • 2,971
  • 9
  • 21
  • "and in the other case the this pointer doesn't need to be dereference because nothing from the class was accessed" might also be worth pointing out not to rely on that, i've not got proof on hand but i'm pretty sure it's an implementation detail whether or not a dereference will happen, either way I think you'd agree that it'd be confusing to see production code that relies on such behaviour? – George Jun 07 '18 at 07:25
  • of course this kind of code should be done as it is undefined behavior but everybody was already pointing that out – Tyker Jun 07 '18 at 07:29