What will happen when I call a member function on a NULL object pointer? [duplicate]

Solution 1:

It's undefined behavior, so anything might happen.

A possible result would be that it just prints "fun" since the method doesn't access any member variables of the object it is called on (the memory where the object supposedly lives doesn't need to be accessed, so access violations don't necessarily occur).

Solution 2:

By the standard, this is undefined behavior and therefore a very bad thing. In reality of most programming platforms (across both X86 and several other architectures) this will run fine.

Why? Consider how class functions are implemented in C++. This isn't a virtual function, therefor this can be a static call to a known address. In x86 assembly, we can see this as

mov A, 0
mov ecx, A
call a__fun

since a__fun requires no instance data, even though it receives a null this pointer, nothing will happen.

Still shitty code and any compiler will scream, but it can run.

Solution 3:

The most likely behavior, on most modern computers, is that it will run, and print "fun", because:

  • C++ doesn't check whether the pointer is NULL before calling the function
  • fun() is not virtual, so there's no need to refer to a vtable to call fun()
  • fun() never access any member variables in A so it doesn't need to dereference the null this pointer.

Solution 4:

We can't know what will. Everything can happen, because the program exposes undefined behavior. See Does invoking a member function on a null instance cause undefined behavior?.