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

后端 未结 5 880
天涯浪人
天涯浪人 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:21

    As a side note, just to compel the differences in architectures, a certain OS developed and maintained by a company known for their three-letter acronym name and often referred to as a large primary color has a most-fasicnating NULL determination.

    They utilize a 128-bit linear address space for ALL data (memory AND disk) in one giant "thing". In accordance with their OS, a "valid" pointer must be placed on a 128-bit boundary within that address space. This, btw, causes fascinating side effects for structs, packed or not, that house pointers. Anyway, tucked away in a per-process dedicated page is a bitmap that assigns one bit for every valid location in a process address space where a valid pointer can lay. ALL opcodes on their hardware and OS that can generate and return a valid memory address and assign it to a pointer will set the bit that represents the memory address where that pointer (the target pointer) is located.

    So why should anyone care? For this simple reason:

    int a = 0;
    int *p = &a;
    int *q = p-1;
    
    if (p)
    {
    // p is valid, p's bit is lit, this code will run.
    }
    
    if (q)
    {
       // the address stored in q is not valid. q's bit is not lit. this will NOT run.
    }
    

    What is truly interesting is this.

    if (p == NULL)
    {
       // p is valid. this will NOT run.
    }
    
    if (q == NULL)
    {
       // q is not valid, and therefore treated as NULL, this WILL run.
    }
    
    if (!p)
    {
       // same as before. p is valid, therefore this won't run
    }
    
    if (!q)
    {
       // same as before, q is NOT valid, therefore this WILL run.
    }
    

    Its something you have to see to believe. I can't even imagine the housekeeping done to maintain that bit map, especially when copying pointer values or freeing dynamic memory.

提交回复
热议问题