Waneck
Waneck

Reputation: 2470

Implementing an overflow-free system stack in C90

I was just reading about how Google Go makes each thread with a reduced stack size by default, and then links to new stacks if an overflow would occur ( see page 16 in here ). I was wondering the best way to do that in C.

I have to say I am no C expert, so there might be a better way to detect a Stack Overflow on C, but giving my ignorance, here's how I thought I would implement it:

The first thing I thought is that every time we have a fresh new stack, we get a stack variable's address, and with that we have roughly the starting stack address. Then we would need to be able to retrieve how much stack space the thread has. This would be possible if the thread isn't the main thread, but I have no idea how we would get this info on C.

Then we would need to check (per function call, it could be) how much of the stack is already used, by retrieving current stack variable address. If we detect a possible stack overflow, we would need to have some way to create a new stack and link to the last one. The only way I thought it could be done in C would be to create a new thread to execute the function we want, and lock the current thread until the function returns its result.

So, would there be a cleaner/better way to implement this?

Upvotes: 8

Views: 837

Answers (2)

Ira Baxter
Ira Baxter

Reputation: 95400

See GCC's split-stack capability. I believe this was originally implemented to support Go. It pretty much works as you suggest.

EDIT: The commentary below discusses another system that does heap-allocation of activation records.

Upvotes: 9

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215457

You can do this - I believe modern gcc may even have an option for it - but it greatly increases the cost of function calls and has very little practical benefit. Especially on modern systems with 64-bit addressing, there's plenty of address space for each thread to have its own stack plenty far from every other thread's stack. If you find yourself using more than logarithmic-scale call recursion, something is wrong with your algorithms anyway...

Upvotes: 2

Related Questions