Reputation: 33
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
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.
Memory allocated by this function is automatically initialized to zero.
Code with undefined behavior can still run flawlessly under certain conditions until these conditions change.
Upvotes: 1
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
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