Frage

I am wondering why the following little program does not cause a NullPointerException. Any ideas? The output is 2x Hello World!!! on my macbook using clang-500.2.79.

#include <iostream>

using namespace std;

class Strange {
public:
    Strange() {}
    virtual ~Strange() {}
    void sayHello() {
        cout<<endl<<"Hello World!!!"<<endl;
    }

};

int main(void) {
    Strange* s = new Strange();
    delete s; s = NULL;
    s->sayHello();
    (*s).sayHello();
    return 0;
}
War es hilfreich?

Lösung 2

I am wondering why the following little program does not cause a NullPointerException.

Because it's C++, not a "managed" language with expensive run-time checks on every operation. You won't get an exception if you dereference a null pointer; you'll get some kind of undefined behaviour.

In this case, the member function doesn't access the object so (on most implementations) it will behave as if the pointer were valid. If it did access the object, then you might get a run-time fault, or memory corruption leading to subtle bugs and sleepless nights.

Avoid pointers and new when you can; use smart pointers and other RAII techniques when you must. If there's any chance that a pointer might be null, then check it before dereferencing it.

Andere Tipps

C++ doesn't have a "NullPointerException." Dereferencing a null pointer is simply Undefined Behaviour and anything can happen.

In your case, sayHello() does not access *this at all, so it happens to work "normally" (on your compiler, optimisation settings, runtime & HW). But that's not guaranteed. Undefined behaviour is simply undefined; the program could just as well crash or order pizza online.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top