Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a local variable exist before a combined declaration/assignment?

Tags:

c

variables

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?

like image 499
gmolau Avatar asked Dec 09 '17 17:12

gmolau


3 Answers

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().

like image 105
ad absurdum Avatar answered Oct 26 '22 07:10

ad absurdum


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).

like image 35
Frankie_C Avatar answered Oct 26 '22 05:10

Frankie_C


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.

like image 38
babon Avatar answered Oct 26 '22 05:10

babon