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

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

    Because most of the programs run in user mode, and the OS runs in kernel mode. The Kernel mode is near to the physical hardware (they say close to the metal). Kernel mode programs (OS, some services, drivers etc) runs in ring 0 of CPU. User mode programs runs on higher ring. User mode programs running on ring N of CPU, cannot access programs or memory running on anything less than N. If they try to, they wont be allowed!

    All programs get their logical address, and OS assigns it. OS does the logical to physical addressing when program tries to read or to write some memory. If program tries to access the address, which it doesn't have permission, the OS will throw the exception. This exception may be handled by program itself (a local exception-handler, in same thread). If not, any attached global exception handler. Debugger may also come into picture, if local EH doesn't handle it. It depends on OS, how/when to route exception to debugger and/or to the global exception handler. It also depends on type of exception (like null-pointer access), if OS allows local/global/debugger to handle it or not. If no one handles it, the OS would terminate the process (and possibly creating crash dump, segmentation fault core dump).

    If the process it not being debugged (Windows specific), and some debugger is installed, OS may allow user to debug it.

    If the kernel mode program does something nasty, it would take down the OS. I'm not Linux guy, so don't know behavior of Linux. But, in case of Windows, BSOD would brighten your monitor with blue color!

提交回复
热议问题