Shiny
Shiny

Reputation: 33

Pointer automatically gets initialized to NULL

Today I came through a strange situation where my uninitialized pointer is automatically initialized to NULL.

Sample Code

class A
{
public:
  A(): ptr1(NULL) {}

  void Fun()
  {
     if (ptr2 != NULL && ptr2->Status())
     {
        ...
        ...
     }
  }

private:
  XYZ* ptr1;
  ABC* ptr2;
};

When I integrated my code with existing project its started crashing at the if condition because of the wild pointer(ptr2). Then I reverted my code and put a break point at the constructor and I can see this pointer(ptr2) is initialized with NULL!!!. How this happens, nobody initialized this pointer and it was running in different PCs(Ubuntu) without any issue for past 1+ years?

Upvotes: 1

Views: 813

Answers (3)

Stacker
Stacker

Reputation: 1190

How this happens, nobody initialized this pointer and it was running in different PCs(Ubuntu) without any issue for past 1+ years?

There are several possible reasons why your application has worked for such a long time.

  • Some compilers/runtimes initialize all memory to zero in debug builds. Maybe you have changed your compile flags?
  • When your application requests additional memory pages from the operating system these are often cleared to zero to prevent leaking arbitrary data from previously run applications. See VirtualAlloc for Windows which states

    Memory allocated by this function is automatically initialized to zero.

  • You may have updated some memory allocator which now works slightly different.

Code with undefined behavior can still run flawlessly under certain conditions until these conditions change.

Upvotes: 1

masoud
masoud

Reputation: 56479

Reading the value of an uninitialized pointer invokes undefined behavior.

Pointers are uninitialized by default (in many cases), however it's possible they get a NULL by chance. Generated code in release mode and debug mode could be different and this is the reason you saw different behavior.

Try to initialize them in the constructor:

A() : ptr1(0), ptr2(0) {}

Moreover, it is interesting to know that you've trapped in a Heisenbug.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234695

ptr2 is indeed not initialised by the constructor, unlike ptr1.

So the behaviour on reading the value of that pointer (let alone dereferencing it) is undefined. One manifestation of that undefined behaviour is your compiler setting it to nullptr for you, another one is crashing.

It's time for you to change your constructor to

A(): ptr1(nullptr), ptr2(nullptr) {}

Upvotes: 4

Related Questions