xyf
xyf

Reputation: 714

How do you make sense of the difference in addresses of local variables residing in a particular stack/function?

I'm trying to figure out whether a stack grows up or down and I see the difference in local variables is positive, indicating it's growing down but curious as to how come the difference is 6 for double and 12 for int? That means the variables are 6 bytes apart (each residing in a specific stack) but not sure what's defining the size here given there's only one variable defined in a function (actually 2 with a function argument).

void stack(double *p) {
    double temp;
    
    if (p == NULL) {
        stack(&temp);
    }
    printf ("Diff: %d\n", p - &temp);  // 6
}
int main() {
    stack(NULL);
    return 0;
}

Upvotes: 0

Views: 39

Answers (1)

Kevin Boone
Kevin Boone

Reputation: 4307

This code shows 4 bytes between ints and 8 between longs, which agrees with what I expect for my platform and compiler.

 int a;
 int b;
 long c;
 long d;
 int d_int = (char *)&a - (char *)&b;
 int d_long = (char *)&c - (char *)&d;
 printf ("distance between ints = %d\n", d_int);
 printf ("distance between longs = %d\n", d_long);

However, packing of data on the stack is architecture- and compiler-dependent. Note all platforms will pack char values next to each other, but will pad them to a word size. It's perhaps best not to read too much into these findings.

Upvotes: 1

Related Questions