1
class Test
{
    public:
        int m_value;
    public:
        void testA() { printf("A\n"); }
        void testB() { printf("B:%d", m_value); }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Test* test = NULL;
    test->testA();
    test->testB();
    return 0;
}

Why this program crashed in test->testB(), it should be crashed in test->testA();

Termininja
  • 6,620
  • 12
  • 48
  • 49
Kid
  • 77
  • 1
  • 6

2 Answers2

4

Calling a member function on a NULL pointer is cause for undefined behavior.

Your run time environment is dealing with the NULL pointer leniently. The call to testA() does not cause any problems since you are not accessing any member variables. The call to testB() crashes since you are trying to access a member variable when this is NULL.

Conceptually, a member function is mapped to a function that has the form:

mangled_testA(Test* this){ ... }

If you call such a function on a NULL pointer, the function gets called with the value of this set to NULL. If you don't access any member variables, you don't notice the error. If you access any member variables, you notice the error right away.

P.S. this behavior is not guaranteed by the language. This is what happens often.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • you mean execute function testA() is OK while "this" pointer is NULL? why? "this" is NULL, how can it find testA() address? – Kid Jul 06 '15 at 12:06
  • thanks,i see. testA() address is not save in "Test", if I change testA() to virtual, it would crash in test->testA(), because "Test" class save the virtual function table at this time? – Kid Jul 07 '15 at 00:13
  • @Kid, If you change `testA()` to a virtual function and then call the function on a NULL pointer, your program will most likely crash. – R Sahu Jul 07 '15 at 03:27
0

I have tried this code and ran it in ideone link to code. The issue is with the setting of test =NULL as the Object pointer is set to null.It means that the object is assigned a NULL value and will generally m_value will contain garbage.Depending on the compiler you are using, it will generate error(run time error as it is dynamic allocation). reference1reference2

Just remove the null and assign value to m_value your code will run fine.It is done so as to avoid memory leaks.

Community
  • 1
  • 1
Anony-mouse
  • 2,041
  • 2
  • 11
  • 23