Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can NULL pointer after "dynamic_cast" actually be dereferenced?

The following code compiles correctly and get the mysterious output:

special Investment function 00000000

(Environment: C++ VS2010)

#include <iostream>
#include <vector>
using namespace std;

class Security {
public:
  virtual ~Security() {}
};

class Stock : public Security {};

class Investment : public Security {
public:
  void special() {
    cout << "special Investment function" << endl;
  }
};

int main() {
  Security* p = new Stock;
  dynamic_cast<Investment*>(p)->special();
  cout << dynamic_cast<Investment*>(p) << endl;
  return 0;
}

How could it be? Dereferencing a NULL pointer and get a "correct" output instead of crash? Is it a special "characteristic" of VS2010?

Now I see. I did a test and it appears that dereferencing "this" in "special" function cause the program to crash.

Thanks for your help.

like image 254
Richard Avatar asked Dec 03 '22 08:12

Richard


1 Answers

Dereferencing a null pointer is undefined behavior - you can get unexpected results. See this very similar question.

In this case Investment::special() is called in a non-virtual way, so you can think the compiler just creates a global function

Investment_special_impl( Investment* this )

and calls it passing a null this pointer as the implicit parameter.

You should not rely on this.

like image 135
sharptooth Avatar answered Dec 08 '22 00:12

sharptooth