Is memory address 0x0 usable?

2019-06-24 00:13发布

问题:

I was wondering... what if when you do a new, the address where the reservation starts is 0x0? I guess it is not possible, but why? is the new operator prepared for that? is that part of the first byte not usable? it is always reserved when the OS starts?

Thanks!

回答1:

The null pointer is not necessarily address 0x0, so potentially an architecture could choose another address to represent the null pointer and you could get 0x0 from new as a valid address. (I don't think anyone does that, btw, it would break the logic behind tons of memset calls and its just harder to implement anyway).

Whether the null pointer is reserved by the Operative System or the C++ implementation is unspecified, but plain new will never return a null pointer, whatever its address is (nothrow new is a different beast). So, to answer your question:

Is memory address 0x0 usable?

Maybe, it depends on the particular implementation/architecture.



回答2:

"Early" memory addresses are typically reserved for the operating system. The OS does not use early physical memory addresses to match to virtual memory addresses for use by user programs. Depending on the OS, many things can be there - the Interrupt Vector Table, Page table, etc.

Here is a non-specific graph of layout of physical and virtual memory in Linux; could vary sligthly from distro to distro and release to release:

http://etutorials.org/shared/images/tutorials/tutorial_101/bels_0206.gif

^Don't be confused by the graphic - the Bootloader IS NOT in physical memory... don't know why they included that... but otherwise it's accurate.



回答3:

I think you're asking why virtual memory doesn't map all the way down to 0x0. One of the biggest reasons is so that it's painfully obvious when you failed to assign a pointer - if it's 0x0, it's pointing to "nothing" and always wrong.

Of course, it's possible for NULL to be any value (as it's implementation-dependent), but as an uninitialized int's value is 0, on every implementation I've seen they've chosen to keep NULL 0 for consistency's sake.

There are a whole number of other reasons, but this is a good one. Here is a Wikipedia article talking a little bit more about virtual addressing.



回答4:

Many memory addresses are reserved by the system to help with debugging.

0x00000000 Returned by keyword "new" if memory allocation failed

0xCDCDCDCD Allocated in heap, but not initialized

0xDDDDDDDD Released heap memory.

0xFDFDFDFD "NoMansLand" fences automatically placed at boundary of heap memory. Should never be overwritten. If you do overwrite one, you're probably walking off the end of an array.

0xCCCCCCCC Allocated on stack, but not initialized

But like a few others have pointed out, there is a distinction between physical memory addresses which is what the OS uses, and logical memory addresses which are assigned to your application by the OS. Example image shown here.