1

I tried this simple code and I'm getting a weird result:

#include <iostream>

class CTest
{
public:
    void Function() { std::cout << "CTest::Function()" << std::endl; }
};

int main()
{
    CTest *pTest = new CTest;
    delete pTest;
    pTest = NULL;
    pTest->Function();
}

Compiled with GCC with these parameters: g++ -O0 Test.cpp -o Test

When I run the program, I get this result:

$ ./Test 
CTest::Function()

How is this possible?

lornova
  • 6,667
  • 9
  • 47
  • 74

1 Answers1

4

Dereferencing a null pointer is undefined behavior, and undefined behavior is sneaky in that sometimes it might seem to work.

In your specific case, it most likely works because it's pure member function call, and the member function doesn't do anything with the objects internal state. If you add a member variable and try to access it in the member function, that would probably cause a crash.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Your answer is reasonable if I just deleted the object and then used it. But I set the pointer to NULL: 0x00000000 (tested by printing it out). How can the compiler dereference it? – lornova Aug 26 '14 at 12:18
  • 2
    @Lorenzo, See the duplicate. – chris Aug 26 '14 at 12:19
  • OK now I understand. The compiler uses the address of the object instance only to access member variables (pointer address + member variable offset), but by calling member functions it doesn't uses the pointer address, but the base address of the class in the code memory section. And I also understand that it is an undefined behavior, a different compiler might use a different strategy. – lornova Aug 26 '14 at 12:22