I recently ran into a C++ problem where a segfault was occurring in code in a stable library that hadn't been changed in a while. For a while, I couldn't figure out what would have broken in that library, and the call site looked perfectly fine. Before I give away the answer, let's take a quick quiz. What does the following code output? (And yes, this is somewhat compiler dependent, so let's pretend we're talking about how g++ works.)

#include <cstdio>
 
class Foo {
  private:
    char *name;
  public:
    void whatami() {
      printf("I am a Foo.\n");
    }
    void whoami() {
      printf("I am %s.\n", name);
    }
};
 
int main(int argc, char **argv){
  Foo *f = NULL;
  f->whatami();
  f->whoami();
}

My first instinct was to say "Segmentation Fault" and nothing else, because line 17 is going to dereference a NULL pointer. It turns out, of course, it's not that simple -- it'll actually print the "I am a Foo" before segfaulting. Clearly, then, the segfault must be on line 18, right? Wrong. Line 11 is where we give up, as f is not dereferenced until then. To see why this is, let's think about the equivalent C code:

#include <stdio.h>
 
typedef struct {
  char *name;
} Foo;
 
void Foo_whatami(Foo *self) {
  printf("I am a Foo.\n");
}
 
void Foo_whoami(Foo *self) {
  printf("I am %s.\n", self->name);
}
 
int main(int argc, char **argv) {
  Foo *f = NULL;
  Foo_whatami(f);
  Foo_whoami(f);
}

As we can see here, the pointer is actually unused by the method "Foo_whatami". But wait, you say, don't we need the address of Foo to resolve the location of the method? No, as whatami and whoami are not virtual methods! Their addresses can be determined by the compiler at compile time. Virtual methods, on the other hand, need a pointer from within the data area of the object to the vtable to resolve addresses. Change whatami to a virtual method, and you'll crash much more efficiently.

So remember, even if the code looks like you're dereferencing the pointer, it may well not be dereferenced until much later!