What happens in OS when we dereference a NULL pointer in C?

后端 未结 5 891
天涯浪人
天涯浪人 2020-11-27 02:56

Let\'s say there is a pointer and we initialize it with NULL.

int* ptr = NULL;
*ptr = 10;

Now , the program will crash since ptr

5条回答
  •  鱼传尺愫
    2020-11-27 03:31

    On CPU which support virtual mermory, a page fault exception will be usually issued if you try to read at memory address 0x0. The OS page fault handler will be invoked, the OS will then decide that the page is invalid and aborts your program.

    Note that on some CPU you can also safely access memory address 0x0.

    As the C Standard says dereferencing a null pointer is undefined, if the compiler is able to detect at compile time (or even runtime) that your are dereferencing a null pointer it can do whatever it wants, like aborting the program with a verbose error message.

    (C99, 6.5.3.2.p4) "If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.87)"

    87): "Among the invalid values for dereferencing a pointer by the unary * operator are a null pointer, an address inappropriately aligned for the type of object pointed to, and the address of an object after the end of its lifetime."

提交回复
热议问题