By memory protection, I mean that the following program will throw a runtime exception on many machines:
#include <iostream>
int main() {
int* my_int = new int[12];
std::cout << my_int[20000];
delete(my_int);
return 0;
}
The program gives the following error:
Exception thrown at 0x00007FF7A467101A in myprogram.exe: 0xC0000005: Access violation reading location 0x000002794CA635C0.
Because each process is given its own virtual memory, other programs are already protected from access violations in my code. It seems to me that correct programs pay a runtime cost because incorrect programs may access unallocated memory.
Why do computers bother protecting against access violations outside of a Debug mode?
CodePudding user response:
C might say that out of bounds access has undefined behaviour, but the platform that it is running on will be deterministic.
The system has to do something when you access a virtual address that isn't mapped. On non-toy systems, raising a memory protection signal is done in hardware, so you can't really say there's a performance penalty.
CodePudding user response:
I'd recommend you learn more about paging, virtual memory and Memory management in general. MMU during the page walk, the CPU will realize the virtual memory being accessed is not mapped. The specific thrown exception is system-dependent. Otherwise you'd have to pre-map every virtual page in the process creation incurring in performance penalty.