Reputation: 407
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.
Upvotes: 4
Views: 228
Reputation: 1619
In a Linux (or other Operating System) process when a subroutine is called, the memory for local variables comes from stack area of the process. Any dynamically allocated memory (using malloc, new, etc.) comes from the heap area of the process. During recursion local memory is allocated from stack area during function call and get cleared when the function execution is done.
The memory is being represented with lowest address being at the bottom and highest being at the top. Here are the steps to find the direction of stack growth in recursion using a quick C code.
#include <stdio.h>
void test_stack_growth_direction(recursion_depth) {
int local_int1;
printf("%p\n", &local_int1);
if (recursion_depth < 10) {
test_stack_growth_direction(recursion_depth + 1);
}
}
main () {
test_stack_growth_direction(0);
}
out put on MAC
0x7fff6e9e19ac
0x7fff6f9e89a8
0x7fff6f9e8988
0x7fff6f9e8968
0x7fff6f9e8948
0x7fff6f9e8928
0x7fff6f9e8908
0x7fff6f9e88e8
0x7fff6f9e88c8
0x7fff6f9e88a8
0x7fff6f9e8888
output on ubuntu
0x7ffffeec790c
0x7ffffeec78dc
0x7ffffeec78ac
0x7ffffeec787c
0x7ffffeec784c
0x7ffffeec781c
0x7ffffeec77ec
0x7ffffeec77bc
0x7ffffeec778c
0x7ffffeec775c
0x7ffffeec772c
The stack is growing downwards on these specific setups as memory addresses are reducing. This depends on the architecture of the system and may have different behavior for other architectures. 0x7fff6f9e8868
Upvotes: 0
Reputation: 258648
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.
Upvotes: 3
Reputation: 500893
Your problem relies on undefined behaviour [1], so anything can happen. You shouldn't even be expecting consistency on a given OS: factors such as changes to compiler options can alter the behaviour.
[1] fun1()
returns the address of a variable on the stack, which is subsequently dereferenced.
Upvotes: 0