Search code examples
segmentation-faultmemory-access

How do programs know if a memory access is allowed?


Wikipedia explains about "segmentation fault" in this way:

A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system).

So, what is the mechanism for a program executor to know at runtime whether a memory the program attempts to get access to is actually allowed to access?


Solution

  • The short answer is that the addresses used by your program (and used by the process running your program) are not the "real" memory addresses. Rather, there is a layer of abstraction between you and the physical memory addresses that is provided by virtual memory and paging.

    Also, your program is split up into "segments" with different purposes, which generally live on different pages. For example, local variables allocated for a single function call live on the stack, whereas memory obtained through 'malloc' resides on the heap.