Why I Hate C++ – Reason #47

What do you expect this code to do?

#include <stdio.h>
 
class Foo {
public:
    void doStuff() {
        printf("hi from Foo!\n");
    }
};
 
int main(int argc, char *argv[]) {
    Foo *f = NULL;
 
    f->doStuff();
    return 0;
}

If you said it would crash because of the NULL pointer, you are wrong. This code will actually print “hi from foo” to the console. Why? Because as long as you are not calling any functions that use instance variables or are virtual, the NULL pointer is never dereferenced. And if you know how C++ handles member functions, you should know exactly why.

For the record, I ended up spending a few hours at work today tracking down an issue that ended up being caused by a NULL pointer call. The bug had actually been lurking for a few releases and only when the method being called was modified to use an instance variable did the problem become exposed.

Advertisements

About this entry