4bh1 4bh1 - 4 months ago 11
Linux Question

C local variable reused

As much as I know after every function call the local variables are discarded. But when I executed this piece of code the variables retain their previous value. What is this behavior?

Compiler: gcc 4.8.4

#include<stdio.h>
void t();
int main(void){
t();
t();
t();
return 0;
}

void t(){
int i;
i++;
printf("%d\n",i);
}


Output:

4bh1@mybox:~/C-fi$ ./test
1
2
3

Answer

The behavior of your program is undefined. i is uninitialized so any use of i besides setting its values is undefined behavior.

Most likely what you are seeing is i gets the same "stack space" allocated to it each time so you are just reusing the previous value.

Do note that when an int(or any type) goes out of scope the compiler does not reset it value to something as that would be wasted cpu cycles. This is why you can see the value increasing as it is just reusing what was in the memory space.