The que开发者_C百科stion is self-explanatory (I think). If a program is accessing memory, say 4 bytes at a time, when does the memory happen to be non-readable, as opposed to say, hold garbage? Thanks.
Whenever the program is not allowed to read it.
This is the job of the MMU to allow or forbid access on memory. This is the job of the OS to specify which program is allowed to access which memory zone.
If you allocate/deallocate/access memory correctly, then you will never see this. You will only encounter this when you have done something wrong.
Typically, malloc is implemented with a sub-allocating memory manager. If you ask malloc for 4 bytes of heap memory, say, then the memory manager in the C runtime will allocate a larger block and then sub-allocate 4 bytes within that block to you. Subsequent requests for small amounts of memory will then be sub-allocated from one of these larger blocks.
You can read and write into areas of these large blocks of memory that have not yet been sub-allocated by malloc. Doing so is of course undefined behaviour. Please don't do this! You can also read and write into sub-blocks that have been freed, so long as the larger block has not been returned to the system. Again, please don't do this.
Most commonly a program will fault with a non-readable memory error (a.k.a. segmentation fault or access violation) when it tries to access an address that has been freed and the block of memory containing that address has been returned to the system. This is known as a stale pointer.
In practice, if you are engaging in correctly aligned read operations only, you have nothing to worry about. On real-world hardware, access granularity is always at the level of pages at least 4k in size. Mathematically, if a pointer p
lies in a valid page, and p
is a multiple of some alignment value m
which divides the page size n
, then
(p+0)/n = (p+1)/n = ... = (p+m-1)/n
i.e. p
, p+1
, ..., p+m-1
all point within the same page.
If p
is misaligned to begin with, you have much bigger portability problems than the possibility of reading from an unmapped or unreadable page.
精彩评论