Dereferencing a null pointer

前端 未结 5 1980
时光说笑
时光说笑 2021-01-18 05:10

Why I can\'t dereference a null pointer? That is, why I can\'t read/write memory which address is simply 0?

Does the base pointer of my process have a different addr

相关标签:
5条回答
  • 2021-01-18 05:20

    Why can't I make a phone call to 00000 000 000? I should be able to do this.

    0 讨论(0)
  • 2021-01-18 05:32

    C 2011 online draft

    6.3.2.3 Pointers
    ...
    3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. 66) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

    66) The macro NULL is defined in <stddef.h> (and other headers) as a null pointer constant; see 7.19.

    Emphasis mine. NULL is defined to be an invalid pointer value that represents a well-defined "nowhere". You can't dereference it because there's nothing to dereference. Note that although the null pointer constant is always 0-valued, the null pointer value doesn't have to be; it can be 0x00000000 or 0xDEADBEEF or something completely different; that's up to the platform.

    TL;DR, NULL doesn't represent address 0; it represents "no address".

    0 讨论(0)
  • 2021-01-18 05:39

    A null pointer is not a pointer to "memory [whose] address is simply 0". It's just a special pointer that doesn't point to anything valid.

    The C language says that there are no requirements on the behaviour of a program that dereferences a null pointer.

    0 讨论(0)
  • 2021-01-18 05:42

    A pointer having a value of NULL should be thought of as something that "points to nothing", instead of something that points to some memory address corresponding to 0.

    0 讨论(0)
  • The VM page that sits at address (void *)0x0 or NULL is by default not mapped in any modern OS, thus dereferencing a NULL pointer will result in a segmentation violation.

    NULL pointers are frequently used as pointers that point nowhere.

    Yes, you can obtain the address of your text, stack and heap bases. For stack this is relatively easy, for text and heap you will need to consult /proc/self/smaps (if you have procfs).

    0 讨论(0)
提交回复
热议问题