Kid
Kid

Reputation: 77

class address is different with value address?

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();

Upvotes: 1

Views: 105

Answers (2)

R Sahu
R Sahu

Reputation: 206607

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.

Upvotes: 3

Anony-mouse
Anony-mouse

Reputation: 2151

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.

Upvotes: 0

Related Questions