Living on a null object

Check this out:

struct S {
   int f(){ return 42; }
};

int main() {
   S *x = (S*) NULL;
   return x->f();
}

What does this do? Does it compile? Does it crash? I’ll give you a second.

Ready? It does compile, OK
But it doesn’t crash.
Why, you may ask
Think about it, you must.

The compiler will mangle S::f and translate this into something like:

struct S {};

int mangled_S_f(struct S *this){
   return 42;
}

int main() {
   S *x = (S*) NULL;
   mangled_S_f(x);
}

Now, in this new “translated” code, what do you think? Will it crash? It won’t, since no one is going to dereference “this”. Crazy, huh? This crazy idiom also allows even crazier things, like C++ objects committing sepuku

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s