How does the operating system detect a stack overflow?

On many operating systems the stack and heap begin at opposite sides of a process's virtual address space and grow toward one another. This allows the stack to expand as much as possible without hitting the heap.

Suppose that I have a program that causes a stack overflow. My current understanding is that this would result in the stack growing uncontrollably toward the heap and eventually hitting it. Is this correct? If it is, how does the operating system detect that a stack overflow occurs? It seems like the OS wouldn't be able to detect that the program was trying to use virtual memory allocated for the heap as part of the stack, since they'd be in contiguous memory regions.

I know that this is operating-system specific, but insight on the mechanism by which this occurs in any operating system would definitely be helpful. This has been bugging me for a while and I can't seem to find any good explanations.


The OS allocates some space to the stack. When the process accesses an unallocated part of the stack, a page fault is raised by the processor and catched by the OS. If the OS believes it's still reasonable to grow the stack, it simply allocates new space for it and returns control to the process. If it's not reasonable, a stack overflow exception is raised.


This is just intuition, but making sure that the stack doesn't interfere with the heap sounds like the job of the JVM. I see no reason why I couldn't make my own terrible programming language where I let the stack begin to overwrite the heap (before crashing).


Stack overflows go backwards in the stack -- they work by overwriting data in already initialized parts of the stack, which is possible precisely because stacks grow downwards.

Thus, the operating system cannot detect this condition, as the process is allowed to modify the initialized parts of its stack at any time it wants.

Extending the stack works by the process using the stack space, and the OS trapping into the page fault handler because no page has been set up. Some OSes allow these accesses only on a "guard page", ie the page immediately before the current stack will trigger reallocation, others look at the contents of the stack pointer register at the time of the fault to see whether this was supposed to be a stack access.

链接地址: http://www.djcxy.com/p/80446.html

上一篇: .net中的堆栈和堆内存分配

下一篇: 操作系统如何检测堆栈溢出?