简体   繁体   中英

Dereferencing a null pointer

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?

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.

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

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

值为NULL的指针应该被认为是“ 无所事事 ”的东西,而不是指向某个对应于0的内存地址的东西。

C 2011 online draft


...
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 , . 将结果指针(称为空指针)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM