Reputation: 5200
What methods do operating systems use to prevent crashes or erratic behavior when one of my programs accidentally leaks memory or stack overflow?
Upvotes: 3
Views: 140
Reputation: 8704
Very good question, thanks for asking. There are three issues that I can think of off the bat. And, for each issue, there are two cases.
Stack overflows: If your program is written in anything but assembly language, the OS can detect stack overflow because all stack operations are software operations. The run-time system manages the software stack and knows when overflow happens.
If you have taken the trouble to write your program in assembly language and you pop the hardware stack in error, well, the OS can't save you. Bad things can happen.
Out-of-bounds memory accesses: When your C++ program starts, the OS sets memory bounds on your behalf into the CPU. If your program tries to access memory outside those bounds, the CPU raises a hardware interrupt. The OS, as it handles the interrupt, can tell you that your program has misbehaved. This is what happens when you try to dereference a NULL pointer, for example.
Your assembly-language program, though, can try to read or write from/into whatever memory it feels like. If your program is polite and was started by the OS in the usual way, then the OS can catch that error. But if your program is evil and somehow started outside the purview of the OS, it can do some real damage.
Memory Leaks: Sorry, nobody can help you here.
Upvotes: 2
Reputation: 81389
OSes don´t generally protect from memory leaks in your program; but once your application ends all its memory is reclaimed. If your application never ended, then the OS would eventually get into trouble when it runs out of memory.
Regarding stack overflows, they can detect that you have gone through your stack size. A posibility is to flag a few pages after the stack as protected memory, if you try to access it then you will get a segfault and your program will be terminated.
Upvotes: 2
Reputation: 263577
Briefly: Memory management.
Typically each process is allocated a limited (but usually adjustable) amount of stack space, so a single process can't use up enough to cause problems for the system as a whole.
And if a process attempts to access memory outside what's been allocated for it, that will (at worst) crash the process itself; this frees up the resources allocated for that process without stepping on other processes.
Upvotes: 3