Can someone help me to understand the output of these program.
int* fun1();
void fun2();
int main()
{
int *p=fun1();
fun2();
printf("%d\n",*p);
return 0;
}
int* fun1()
{
int i=10;
return &i;
}
void fun2()
{
int a=100;
printf("%d\n",a);
}
It is 100 100 on windows and 100 10 on Linux. Windows output I am able to justify due to the fact that local variables are allocated on stack. but how come it is 100 10 in Linux.
Returning a pointer to a stack-allocated variable that went out of scope and using that pointer is undefined behavior, pure and simple.
But I’m guessing the answer “anything can happen” won’t cut it for you.
What happens is that on *nix the memory isn’t recycled so it’s not overwritten yet, and on win it is. But that’s just a guess, your best course of option is to use a debugger and walk through the assembler code.