Why doesn't the OS crash if I dereference a null pointer?

后端 未结 9 1503
慢半拍i
慢半拍i 2021-01-21 01:21

Dereferencing a null pointer results in undefined behavior. In practice it usually means that my program will crash. But why doesn\'t the OS crash? Because if my progra

9条回答
  •  不要未来只要你来
    2021-01-21 02:11

    The C++ standard doesn't define the behaviour, either to guarantee a crash, or to do anything else. That doesn't prevent the OS from defining the behaviour - it's not a C++ program, so it doesn't have to abide by the "rules"[1] of C++ programs. Even so, the OS won't dereference the pointer itself.

    On most modern platforms, accessing the target of the dereferenced pointer will cause the memory-management hardware to raise an exception (often called a "segmentation fault" or "protection fault"). This is caught by the kernel, which can determine which process did it, and either kill the process, or send it a signal.

    So, on such a platform, the default behaviour of a process that dereferences a null pointer will be to crash; there is no reason whatsoever for the OS itself to crash.

    [1] By which I mean the informal "rules" that a program should be well-formed and avoid undefined behaviour - not to be confused with the formal "rules" for C++ implementations specified by the language standard.

提交回复
热议问题