0

The following code gives me a warning "null pointer dereference" despite checking the pointer value before casting:

struct ID { virtual ~ID() = default; };
struct IF { virtual void g() = 0; };
struct F : IF { void g() {} };
struct D : ID, F { };

int main() {
    D* d;
    if (d) static_cast<IF*>(d)->g();
}

Is it based on using uninitialized pointer value with -O2 optimization mode or static_cast really can result in null pointer value for non-null argument (e.g. when multiple inheritance is in action)?

αλεχολυτ
  • 4,792
  • 1
  • 35
  • 71
  • 1
    `d` is uninitialized so dereferencing it is undefined behavior. See [Where exactly does C++ standard say dereferencing an uninitialized pointer is undefined behavior?](https://stackoverflow.com/questions/4285895/where-exactly-does-c-standard-say-dereferencing-an-uninitialized-pointer-is-un). *"Undefined behavior means anything can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based up) on the output of a program that has UB."* – Jason Dec 25 '22 at 12:48
  • Also [Consistency of undefined behavior for a fixed compiler](https://stackoverflow.com/questions/74155360/consistency-of-undefined-behavior-for-a-fixed-compiler/74166343#74166343) – Jason Dec 25 '22 at 12:52
  • Change `D* d;` to `D* d{};` to get rid of the undefined behavior, and to get the behavior (I presume) being attempted. – Eljay Dec 25 '22 at 12:59
  • For polymorphic cast use dynamic_cast unless you are totally sure you're dealing with a derived instance (which in my designs is never, since I don't want to rely on that) – Pepijn Kramer Dec 25 '22 at 13:18
  • 2
    The undefined behavior here is for actually already reading the indeterminate value of the uninitialized `d` in `if(d)`. The compiler is not required to assume that the value read in `if(d)` is consistent with the value used in `static_cast(d)` because it is indeterminate. So in that sense the warning message isn't incorrect. However it should really warn about the read of the uninitialized value. – user17732522 Dec 25 '22 at 13:25

0 Answers0