Difference between dereferencing NULL pointer and uninitialised pointer

前端 未结 3 882
傲寒
傲寒 2020-12-22 14:01

On code blocks(C++)

#include
using namespace std;
int main(){
    int *p;
    cout<<*p;
}

produces garbage value

3条回答
  •  鱼传尺愫
    2020-12-22 15:05

    Your expectation of a runtime error is flawed.

    Dereferencing an uninitialised/invalid pointer with arbitrary value can do anything at all.

    That means the potential symptoms range from:

    • nothing happens
    • something happens
    • a runtime error happens
    • your source code is spontaneously edited to use proper standard headers instead of misguidedly hacking in implementation "bits"
    • your attitude in the comments section is magically improved
    • your cat is murdered
    • your cat is not murdered
    • your cat is murdered and not murdered
    • your cat murders itself
    • a black hole opens inside your cat
    • a cat opens up inside a black hole

    and so on.

    This is true for dereferencing NULL, too, but modern commodity hardware tends to treat NULL dereferences specially, usually guaranteeing a segmentation fault to aid in diagnostics. Obviously, a CPU cannot do that for arbitrary pointer values, because they may be valid as far as it knows!

提交回复
热议问题