Stack Usage – How Much Stack Usage is Too Much?

memory usagestackstackoverflow

Lately when I've been writing C or C++, I'll declare all my variables on the stack just because it's an option, unlike with Java.

However, I've heard that it's a bad idea to declare large things on the stack.

  1. Why exactly is this the case? I figure stack overflow is involved, but I'm not very clear on why that happens.
  2. How much stuff on the stack is too much?

I'm not trying to put 100MB files on the stack, just a dozen kilobyte arrays to use as string buffers or whatever. Is this too much stack usage?

(Sorry if duplicate, searching for stack kept giving references to Stack Overflow. There isn't even a call stack tag, I just used the abstract one.)

Best Answer

It depends on your operating system. On Windows, the typical maximum size for a stack is 1MB, whereas it is 8MB on a typical modern Linux, although those values are adjustable in various ways. If the sum of your stack variables (including low-level overhead such as return addresses, stack-based arguments, return value placeholders and alignment bytes) in the entire call stack exceeds that limit, you get a stack overflow, which typically takes down your program without any chance at recovery.

A few kilobytes are usually fine. Tens of kilobytes is dangerous because it starts to sum up. Hundreds of kilobytes is a very bad idea.