setrecursionlimit

Gregory Ewing greg.ewing at canterbury.ac.nz
Thu May 19 05:00:02 EDT 2016


Steven D'Aprano wrote:
> I don't really understand why the system can't track the current top of the
> stack and bottom of the heap, and if they're going to collide, halt the
> process.

That effectively *is* what it does.

The reason it manifests as a segfault is because of the way it
goes about detecting the heap/stack collision. It would be very
expensive to explicitly check for this every time something is
pushed or popped on the stack, so what OSes typically do instead
is reserve a buffer zone of unmapped memory between the stack
and the heap. If the stack overflows, you end up trying to
reference memory in the unmapped area, and a segfault results.

This is not foolproof -- if you allocate a *really* big stack
frame, you could leap right over the buffer zone and clobber
the heap. But it works well enough most of the time and
succeeds in stopping the program before it accidentally
launches the nuclear missiles.

Hardware support for stack bounds checkinbg would of course make
all this easier and more reliable, but the x86 architecture
doesn't provide anything like that, unfortunately.

-- 
Greg



More information about the Python-list mailing list