Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Pointer Behavior

Tags:

c++

Take the following struct and class:

struct TestStruct
{
};

class TestClass
{
public:
    TestStruct* testStruct;
};

Do the following in main:

TestClass testClass;
if (testClass.testStruct == NULL)
    cout << "It is NULL." << endl;
else
    cout << "It is NOT NULL.";

The output will be: It is NOT NULL..

However, if I instead do this:

TestClass testClass;
if (testClass.testStruct == NULL)
    cout << "It is NULL." << endl;
else
    cout << "It is NOT NULL." << endl << testClass.testStruct;

The output will be: It is NULL..

Interestingly enough, if I do this (fundamentally the same as above):

TestClass testClass;
if (testClass.testStruct == NULL)
{
    cout << "It is NULL." << endl;
}
else
{
    cout << "It is NOT NULL." << endl;
    cout << testClass.testStruct;
}

The output will be:

It is NOT NULL.
0x7fffee043580.

What is going on?

like image 204
wjm Avatar asked May 31 '26 04:05

wjm


1 Answers

Your pointer is not initialized when you declare testClass. You experience here an undefined behaviour. The value of the pointer will be the last value that was contain in the memory section where it is stored.

If you wanted it to always be NULL, you would need to initialize it in the constructor of your class.

class TestClass
{
public:
    TestClass(): testStruct(NULL) {}
    TestStruct* testStruct;
};
like image 104
tomahh Avatar answered Jun 01 '26 17:06

tomahh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!