How does the operating system detect stack overflow?

On many operating systems, the stack and heap begin on opposite sides of the virtual address space of the process and grow towards each other. This allows the stack to expand as much as possible without hitting the heap.

Suppose I have a program that causes a stack overflow. My real understanding is that this will cause the stack to grow uncontrollably to the heap and ultimately hit it. It's right? If so, how does the operating system detect that a stack overflow occurs? It seems that the OS will not be able to detect that the program was trying to use the virtual memory allocated for the heap as part of the stack, since they would be in adjacent memory areas.

I know that it depends on the operating system, but understanding the mechanism by which this happens on any operating system will definitely be useful. It annoyed me for a while, and I can not find any good explanations.

+3
source share
4 answers

OS allocates some space on the stack. When a process accesses an unallocated part of the stack, page crashes are picked up by the processor and the OS is caught. If the OS believes it is still prudent to expand the stack, it simply allocates new space for this and returns control to the process. If this is not reasonable, an exception is thrown.

+3
source

, , , JVM. , , ( ).

+1

- , , , .

, , , .

, . " ", , , , , .

+1

MMU ( ), "" , . MMU, , MMU .

http://en.wikipedia.org/wiki/Memory_management_unit

, , SO. .

I also saw a different approach using protective words. The stack for each process was distributed on the heap and filled with protective shields (something like 0xc0cac01a). Thus, it was easy to get the stack size for each process by simply counting the protective words. The operating system caused a panic if there was not even one protective word.

+1
source

Source: https://habr.com/ru/post/1790392/


All Articles