I have the following C code:
void testA() {
int x = 56;
printf("Address of x = 0x%x - Value of x = %d\n",&x,x);
}
void testB() {
int y;
printf("Address of y = 0x%x - Value of y = %d\n",&y,y);
}
int main() {
testA();
testB();
return 0;
}
The print result is the following:
Address of x = 0x61fdec - Value of x = 56
Address of y = 0x61fdec - Value of y = 56
Why does testB()
's local variable y
has the same address as testA()
's local variable x
and inherits its value as well? They're not even in the same scope and none of them is a global variable.
C 2018 6.2.4 2 says:
The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it…
Objects whose identifier is declared inside a function without static
or extern
have automatic storage duration. The C implementation reserves memory for them automatically and releases the reservation automatically.
The lifetime begins when execution of the block the object is in begins (if it is not a variable length array) or when execution reaches the declaration (if it is a variable length array).
When the body of testA
starts executing, memory is reserved for x
.
Then you put 56 in x
.
Then the function returns, and the block x
is in stops executing. So the memory is no longer reserved for it.
Nobody comes along and cleans up that memory. Your mommy does not clean up after you, in the real world or in the computer.
Somebody might come along and use that memory. They ought to initialize it themself, but, if they do not, they might see what you put into that memory.
When testB
starts executing, memory is reserved for y
. Due to the way these reservations are organized, it is easy for that to be the same memory that was previously reserved for x
. Then the value that appears to be in y
might be the same value you put in x
.
When you turn on optimization, the compiler might redesign the program and eliminate this effect. Or it might not.