2

I try to verify my understand of the stack memory layout in C by compiling following code and inspect the address in gdb. I only record the least significant digits, the higher ones are the same. The outputs are generated by using the

print \u &a 

Here is a simple test code:

void test(int a,int b)
{
  int c = a;
  int d = b;
  printf("%d,%d\n",c,d);
}

int main()
{
  int x = 1;
  int y = 2;
  test(x,y);
  return 0;
}

If I look at the test function frame, I have following results,

&b: 6808 &a: 6812

&c: 6824 &d: 6828

$rbp: 6832 (frame pointer).

I am confused. Shouldn't function parameters sit at higher memory address with respect to the local variables. Can someone explain this in detail please?

Edit:
If I print the memory out like:

printf("&a:%p,&b:%p\n",(&a),(&b));
printf("&c:%p,&d:%p\n",(&c),(&d));

I got

&a:0x7fff4737687c,&b:0x7fff47376878
&c:0x7fff47376888,&d:0x7fff4737688c

It turns to be in b a c d order. There is a 8 byte gap between end of a and beginning c. I guess it shall be the return address?

Yun
  • 3,056
  • 6
  • 9
  • 28
small_potato
  • 3,127
  • 5
  • 39
  • 45

1 Answers1

0

As per the flow of a function, first arguments are allocated and then the internal arguments. Your concern is based on the presumption that stack grows upwards (which is not necessary).

Please follow the below link for more understanding: Does stack grow upward or downward?

Community
  • 1
  • 1
thepace
  • 2,221
  • 1
  • 13
  • 21