Could I ever want to access the address zero?

前端 未结 17 3001
花落未央
花落未央 2020-11-29 00:38

The constant 0 is used as the null pointer in C and C++. But as in the question \"Pointer to a specific fixed address\" there seems to be some possible use of assigning fixe

17条回答
  •  感情败类
    2020-11-29 01:07

    It may surprise many people, but in the core C language there is no such thing as a special null pointer. You are totally free to read and write to address 0 if it's physically possible.

    The code below does not even compile, as NULL is not defined:

    int main(int argc, char *argv[])
    {
        void *p = NULL;
        return 0;
    }
    

    OTOH, the code below compiles, and you can read and write address 0, if the hardware/OS allows:

    int main(int argc, char *argv[])
    {
        int *p = 0;
        *p = 42;
        int x = *p; /* let's assume C99 */
    }
    

    Please note, I did not include anything in the above examples. If we start including stuff from the standard C library, NULL becomes magically defined. As far as I remember it comes from string.h.

    NULL is still not a core C feature, it's a CONVENTION of many C library functions to indicate the invalidity of pointers. The C library on the given platform will define NULL to a memory location which is not accessible anyway. Let's try it on a Linux PC:

    #include 
    int main(int argc, char *argv[])
    {
            int *p = NULL;
            printf("NULL is address %p\n", p);
            printf("Contents of address NULL is %d\n", *p);
            return 0;
    }
    

    The result is:

    NULL is address 0x0
    Segmentation fault (core dumped)
    

    So our C library defines NULL to address zero, which it turns out is inaccessible. But it was not the C compiler, of not even the C-library function printf() that handled the zero address specially. They all happily tried to work with it normally. It was the OS that detected a segmentation fault, when printf tried to read from address zero.

提交回复
热议问题