In C/C++, is the memory on the stack freed after finishing a scope block and can it be reused?
For example, let's say I have 100 free bytes on the stack after enetering the function.
void function(void)
{
{
uint8_t buffer1[80];
// Do something with the buffer
}
{
uint8_t buffer2[80];
// Do Something with the buffer
}
}
Can enough memory be allocated for buffer2 or is the memory used for buffer1 only freed at the end of the function?
What happens is compiler dependent ...
either_buffer[80];)sp) is decremented. The buffer is acted upon. The stack pointer is incremented.Of course, things placed in the function's stack frame are only "freed" when the function returns.
(1) Separate buffers in the function stack frame (pseudo code):
(2) A single area in the function stack frame (pseudo code):
(3) Stack pointer is incremented/decremented as needed (pseudo code):
(4) What actually happens (for x86, with gcc 8.3.1):
Here is the assembly code:
This is the equivalent of the following pseudo code:
For
clang7.0.1, we get:For
c++8.3.1, it is similar togcc:For
gcc, with-m32, we get:For clang, with
-m32, we get:The above [actual] asm is generated without optimization, so with (e.g.
-O2), the code could be slightly different [not shown].As it is, the
gcccode seems to be slightly more optimal than theclangcode by default.