Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
today i attended a seminar on basic C coding and we stumbled upon a brainteaser, that none of the present assistants could answer me to my content.
the code is:
#include <studio.h>
int *f(int a) {
int b = 2 * a;
return &b;
}
int main(void) {
int *p4;
int *p8;
p4 = f(4);
p8 = f(8);
printf("p4: %i / p8: %i\n", *p4, *p8);
}
i know what is wrong with the code and i would never myself code something like that, but it is still interesting.
the output is:
p4:16 / p8:16
intended was of course
p4:8 / p8:16
what i first expected was that we’d get an error because after the functon f is through &b should not exist anymore (variable scope).
the assistants explained it as ‘lucky punch’ that there is still something in the memory at that position, but that did not really do it for me.
i thought id post it here and see if someone has a better explanation.
IMPORTANT: this is not a question of how to add 2 ints in a function – i am fairly capable of that – its: why is the number 16 stored at *p4 when retrieving it for the printf.
looking forward to inspiring answers,
sebastian
With undefined behavior – anything can happen.
You are returning a pointer to a variable that is destroyed, and then you access that memory location. That is the UB.