How is the stack allocated for a process on Linux

Can someone help me understand the output of this 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); } 

This is 100 100 on windows and 100 10 on Linux. Exit Windows I can justify due to the fact that local variables are allocated on the stack. but why is it 100 100 in linux.

+4
source share
4 answers

Returning a pointer to a stack-highlighted variable that is out of scope and using this pointer is undefined behavior, clean and simple.

But I guess the answer โ€œanything can happenโ€ will not cut it for you.

What happens is that on * nix the memory is not recyclable, so it has not been overwritten yet, and there is a win. But this is just an assumption, your best option is to use a debugger and go through the assembler code.

+3
source

Your problem depends on the behavior of undefined [1], so anything can happen. You should not even expect consistency in a given OS: factors such as changes to compiler options can change behavior.

[1] fun1() returns the address of the variable on the stack, which is then dereferenced.

0
source

Crashed pointer Problem , hence undefined behavior.

0
source

In a Linux process (or other operating system), when a subroutine is called, the memory for local variables comes from the process stack area. Any dynamically allocated memory (using malloc, new, etc.) comes from the process heap area. During recursion, local memory is allocated from the stack area during a function call and is cleared when the function is executed.

The lowest address located at the bottom is displayed in the memory, and the top is at the top. Below are the steps to find the direction of stack growth in recursion using the fast 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 on MAC

 0x7fff6e9e19ac 0x7fff6f9e89a8 0x7fff6f9e8988 0x7fff6f9e8968 0x7fff6f9e8948 0x7fff6f9e8928 0x7fff6f9e8908 0x7fff6f9e88e8 0x7fff6f9e88c8 0x7fff6f9e88a8 0x7fff6f9e8888 

ubuntu output

 0x7ffffeec790c 0x7ffffeec78dc 0x7ffffeec78ac 0x7ffffeec787c 0x7ffffeec784c 0x7ffffeec781c 0x7ffffeec77ec 0x7ffffeec77bc 0x7ffffeec778c 0x7ffffeec775c 0x7ffffeec772c 

The stack grows on these specific settings as memory addresses decrease. It depends on the system architecture and may have different behavior for other architectures. 0x7fff6f9e8868

0
source

Source: https://habr.com/ru/post/1380367/


All Articles