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

后端 未结 9 1415
慢半拍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:02

    Because the OS has to do something, and crashing would make for a rather bad user experience.

    The OS isn't being written to run on the abstract machine of the C standard. It's being written for real hardware that behaves in real ways to different situations that the standard calls "undefined," so it can (and really must) take those real behaviors into account. If it didn't, the operating system would perform differently on different hardware, which kind of defeats the purpose of having an OS, doesn't it?

    And before you say "undefined behavior is undefined, let the user of bad code wreck what they want," imagine the security problems of a single accidental buffer overrun being able to segfault an entire server.

提交回复
热议问题