Dereferencing a null pointer

2020-04-04 15:01发布

问题:

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 address? If yes, is there a way to obtain the lower memory adders available for the default heap of my process?

回答1:

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.



回答2:

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



回答3:

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).



回答4:

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.



回答5:

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".