Several years ago, I put together this little memory address exploration for my students to help them to understand pointers, arrays, the stack, and the heap.
I just compiled and ran it in a new environment (gcc on a AWS Linux server) and the order of the parameters for foo are different from what I would expect. The local function variables (d1 and e1) now have a higher address in comparison to the function parameters (a1, b1, and c1).
The addresses for the parameters / variables in function foo are listing as:
&a1: fa2740fc
&b1: fa2740f0
&c1: fa2740e8
&d1: fa27410c
&e1: fa274100
Any thoughts on why variables d1 and e1 have higher addresses than a1, b1, and c1?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int* foo (int a1, int b1[], int *c1)
{
int d1 = *c1 + a1;
int *e1;
e1 = malloc (sizeof(int));
printf ("5) Addresses of arguments/variables of foo:
");
printf (" Update your stack sketch.
");
printf (" &a1: %x
", &a1);
printf (" &b1: %x
", &b1);
printf (" &c1: %x
", &c1);
printf (" &d1: %x
", &d1);
printf (" &e1: %x
", &e1);
printf ("6) Values of arguments/variables in foo:
");
printf (" Include these on your stack sketch as well.
");
printf (" a1: %x
", a1);
printf (" b1: %x
", b1);
printf (" c1: %x
", c1);
printf (" d1: %x
", d1);
printf (" e1: %08x
", e1);
printf ("7) *c1 == %x, why? Explain using your stack drawing.
", *c1);
printf ("8) e1 is a reference to an integer, much like c1. Why is e1 so
");
printf (" different in value?
");
return e1;
}
int main ()
{
int a = 5;
int b[] = {8, 14, -7, 128, 12};
int c = 10;
int d = 14;
printf ("1) Locations...
");
printf (" Use these locations to sketch the stack.
");
printf (" &a: %x
", &a);
printf (" &b: %x
", &b);
printf (" &c: %x
", &c);
printf (" &d: %x
", &d);
printf ("2a) Values:
");
printf (" Why does b != 8?
");
printf (" a: %x
", a);
printf (" b: %x
", b);
printf (" c: %x
", c);
printf (" d: %x
", d);
printf ("2b) Values:
");
printf (" What memory address is *b accessing?
");
printf (" *b: %x
", *b);
printf ("3) Notice that the following increase by 4 each, why?
");
printf (" &(b[0]): %x
", &(b[0]));
printf (" &(b[1]): %x
", &(b[1]));
printf (" &(b[2]): %x
", &(b[2]));
printf (" &(b[3]): %x
", &(b[3]));
printf ("4) Pointers can be added, but the addition might have interesting results.
");
printf (" Explain why b + 1 != b + 1 in the normal way of thinking about addition.
");
printf (" b: %x
", b);
printf (" b+1: %x
", b+1);
printf (" b+2: %x
", b+2);
printf (" b+3: %x
", b+3);
foo (a, b, &c);
}
question from:
https://stackoverflow.com/questions/66050493/order-of-parameter-and-variables-on-stack-in-c