Understanding Stack Frames in C

I am trying to understand the stack frame in C, so I wrote simple C code to parse the stack frame.

  • First of all, fun1 () returns the address of a local variable that is initialized from 10 to ptr, which leads to a warning, but that’s fine ... If I print the * ptr value, now it prints 10, even that is fine ...

  • Next, fun2 () returns the address of a local variable that is not even initialized, and if I try to print the value * ptr, now it prints 10 regardless of whether I return the address a or b ...

  • To understand what is really going on here, I used gdb. Using gdb, I started step-by-step debugging, and when I reached the line "return & a" in fun2 (), I tried to print the address b, print & b, but printed Unable to accept the address "b", which is not a value of l.

I do not understand, when I try to print the address a, print & a it prints absolutely for sure, why not the address b. * Why is not b the value of l when a is?

# include <stdio.h> int * fun1() { int a = 10; return &a; } int * fun2() { int a; int b; return &a; // return &b; } int main () { int *ptr; ptr = fun1(); ptr = fun2(); printf ("*ptr = %d, fun2() called...\n", *ptr); return 0; } 
+6
source share
2 answers

The compiler optimizes the code in fun2 .

If you come back &a , it is optimized int b; . If you come back &b , it is optimized int a; . If you add some dummy calculations, you will see that the addresses of the returned values ​​will be different.

 int * fun2() { int a; int b; int* p = &a; p = &b; return p; } 

Change main to print the return values ​​of fun1 and fun2 .

 int main () { int *ptr; ptr = fun1(); printf ("ptr = %p, fun1() called...\n", ptr); ptr = fun2(); printf ("ptr = %p, fun2() called...\n", ptr); printf ("*ptr = %d, fun2() called...\n", *ptr); return 0; } 

When I run this code, I get the following output:

  ptr = 0x7ffff98c70ec, fun1 () called ...
 ptr = 0x7ffff98c70e4, fun2 () called ...
 * ptr = 32749, fun2 () called ...
+3
source

It compiles for me just fine, returning the address to b. But you should not return the address of a local variable. Check out this link .

0
source

All Articles