0
#include <iostream>
int main() {
    int* pt;
    std::cout << pt << std::endl;
    if(pt)
        std::cout << "true" << std::endl;
    else
        std::cout << "false" << std::endl;
    return 0;
}

This code fragment evaulate to false. What is more it prints 0 in

    std::cout << pt << std::endl;

I thought that uninitialized pointers points to some random address, which may contain garbage value. In this case it points to 0 value like i would assign it to nullptr. Could someone clarify this for me?

1 Answers1

1

This code invokes Undefined Behavior (UB), since the pointer is used uninitialized.

The compiler should emit a warning, when a warning flag is used, like -Wall for example:

warning: 'pt' is used uninitialized in this function [-Wuninitialized]
     std::cout << pt << std::endl;
                  ^~

It just happens, that at this run, on your system, it had the behavior of a null pointer. That means that the garbage value the pointer takes, happens to be 0. However, notice that, kernel zeroes appear relatively often.

gsamaras
  • 71,951
  • 46
  • 188
  • 305