There isn't a portable way. However, there are a few nonportable solutions.
First, as others have mentioned, Windows provides a nonstandard __try
and __except
framework called Structured Exeption Handling (your specific answer is in the Knowledge Base).
Second, alloca
-- if implemented correctly -- can tell you if the stack is about to overflow:
bool probe_stack(size_t needed_stack_frame_size)
{
return NULL != alloca(needed_stack_frame_size);
};
I like this approach, because at the end of probe_stack
, the memory alloca
allocated is released and available for your use. Unfortunately only a few operating systems implement alloca
correctly. alloca
never returns NULL
on most operating systems, letting you discover that the stack has overflowed the old fashioned way: with a spectacular crash.
Third, UNIX-like systems often have a header called ucontext.h
with functions to set the size of the stack (or, actually, to chain several stacks together). You can keep track of where you are on the stack, and determine if you're about to overflow. Windows comes with similar abilities a la CreateFiber
.