Search code examples
c++coperating-systemsegmentation-faultinternals

Pointer indirection check for invalid memory access and segmentation fault


struct A { int i; };
...
A *p = (A*) (8); // or A *p = 0;
p->i = 5;    // Undefined Behavior according C/C++ standard

However, practically most of the system would crash (segmentation fault) for such code.

Does it mean that all such Architectures/Systems have a hidden check for pointer indirection (i.e. p->) to verify if it's accessing a wrong memory location ?

If yes, then it implies that even in perfectly working code we are paying the price for that extra check, correct ?


Solution

  • No, not correct. Those exact same checks are absolutely needed on valid memory accesses for two reasons:

    1) Otherwise, how would the system know what physical memory you were accessing and whether the page was already resident?

    2) Otherwise, how would the operating system know which pages of physical memory to page out if physical memory became tight?

    It's integrated into the entire virtual memory system and part of what makes modern computers perform so amazingly well. It's not any kind of separate check, it's part of the process that determines which page of physical memory the operation is accessing. It's part of what makes copy-on-write work. (The very same check detects when a copy is needed.)