I'm currently trying to debug a small C program whose general structure looks like this:
int some_function(...) {
...
size_t buf_len = some_other_function(...)
...
}
main() {
...
int foo = some_function(...)
...
}
I've set a breakpoint at some_function()
(using lldb). However, if I inspect the stack frame at this breakpoint it shows the variable buf_len
already existing with the local scope and even having an arbitrary(?) value. How is this possible if the variable is not declared anywhere before this function?
According to §6.2.4/6 of the C11 Draft Standard:
For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way.
So it should come as no surprise that buf_len
is visible in the debugger the moment execution enters some_function()
.
During compilation each variable is added to the symbol table. For this reason any reference to a variable will resolve only if it was already declared, and inserted in the symbol table. If you reference a variable before its declaration you'll get an error of undefined reference.
But the space for all the automatic variables is allocated all-in-one in the stack during the function prolog (i.e. in IA32-64 architecture the space required by all automatic variables is obtained subtracting that space to the stack pointer register in the stack frame). The required space is computed by the compiler by summing the memory space required for all automatic variables present in the symbol table for that function.
Practically when stack frame is created on function entry all automatic variables are there, even if used after.
In some cases the variables are not allocated if the compiler optimize them out, the compiler optimizing the code choose a different way to use the variable suppressing it (i.e. using a register or simplifying the flow and removing intermediate storage).
A stack frame contains the args passed in along with the local variables and some other stuff. Look at this, especially the "Structure" section. A breakpoint can not make you stop just between two functions. At a function call, a stack frame is one of the first things created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With