Does the C standard have any guarantees on the amount of stack space used?

Does the C standard guarantee amount of stack used?

No guarantees whatsoever exist for this. The C standard does not mention concepts like stacks. You can even write C for low level CPUs that completely lack a stack.

The C standard does however guarantee that uint8_t is 1 byte large and that 1 byte is 8 bits on your system (or otherwise uint8_t wouldn't be available).

How much stack space would the following C code occupy at run-time?
Could some compiler decide to allocate 16000 + 32000 = 48kB stack space for both buffers?

System-specific, but also depends on exactly how the function is written and what optimizations that take place. Generally though, real world systems allocate room for as much stack as the function requires, given all possible execution paths. So it is quite likely that many compilers would allocate 16k + 32k.

But who cares, since it doesn't make sense to allocate that large amount of memory on the stack in any known system. Not on high-end, PC-like systems and certainly not on memory-restricted embedded systems. You'll get stack overflows all over the place.

The general rule of thumb in embedded is to never allocate any form of buffers on the stack, but always with static storage duration. On PC-like systems, heap allocation is another option.


@Lundin provided an excellent answer. But I wanted to answer from a slightly different perspective.

The C standard basically guarantees behavior of the code. It does not guarantee much of how it is done. It is possible (don't know how likely) that it will even move the buffer declaration outside the if statement. It may also allocate more memory than specified. It is also allowed to allocate less if it does not break anything. Typically, unused variables are removed by the optimizer. The optimizer also often inline small functions instead of calling them, and it may change a printf("\n") to a puts(""). The compiler is free to do anything as long as the observable behavior of the code remains the same.

So no, you don't have any guarantees in this case.

But one thing to consider here. You want to declare a different sized buffer depending on an if statement. Let's say that these extra 16kB would invoke a stack overflow. What do you do if you have less than 32kB of stack left and the else branch needs to be executed? Of course it depends on how the code is used in reality, but it is definitely worth considering. To me, this is a pretty strong code smell.

Tags:

C

Stack

Embedded