Why C++ Recognizes an uninitialized Raw Pointer (or say a daemon) as true?

Why the following code produces a seg-fault

//somewhere in main
    ...
    int *pointer;
    if(pointer)
        cout << *pointer;
    ...

But slightly changed following code doesn't

//somewhere in main
    ...
    int *pointer = nullptr;
    if(pointer)
        cout << *pointer;
    ...

the question is what in C++ makes an uninitialized pointer true - and leads to a crash


Solution 1:

Why C++ Recognizes an uninitialized Raw Pointer (or say a daemon) as true?

The behaviour may appear to be so, because the behaviour of the program is undefined.

Why the following code produces a SEGMENTATION FAULT!!!

Because the behaviour of the program is undefined, and that is one of the possible behaviours.


But slightly changed following code doesn't

Because you don't read an indeterminate value in the changed program, and the behaviour of that program is well defined, and the defined behaviour is that the if-statement won't be entered.


In conclusion: Don't read uninitialised variables. Otherwise you'll end up with a broken, useless program.

Although a compiler isn't required to diagnose undefined behaviour for you, luckily high quality compilers are able to detect such simple mistake. Here is example output:

warning: 'pointer' is used uninitialized [-Wuninitialized]
if(pointer)
   ^~

Compilers generally cannot detect all complex violations. However, runtime sanitisers can detect even complex cases. Example output:

==1==WARNING: MemorySanitizer: use-of-uninitialized-value

Aside from reading uninitialised values, even if it was initialised, if (pointer) doesn't necessarily mean that you're allowed to indirect through the pointer. It only means that the pointer isn't null. Besides null, other pointer values can be unsafe to indirect through.

Solution 2:

Because your unitialized Pointer gets implicitly converted to a boolean. Where 0 converts to false and every other value to true.