Jake
Jake

Reputation: 16837

Function argument and variable addresses in C

I have the following program:

#include <stdio.h>

void func(char *str) {

   int a = 4;   

   printf("\n str Address: 0x%8X\n", (unsigned int)&str);
   printf("\n a Address: 0x%8X\n", (unsigned int)&a);
}

void main()
{
    char c = 'y';
    func(&c);
}

When I run the program, I get the following result:

str Address: 0x43570EB8

a Address: 0x43570ECC

My understanding is that the stack in Linux grows from high address to low address. Also str as an argument would be pushed first on the stack. If that is the case, why is str address lower than address for variable a ? Am I printing the addresses in an incorrect way ?

Upvotes: 0

Views: 230

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222640

Most likely the parameter str is passed in a register. Normally, it would be used from that register and would never exist on the stack. Because your code takes the address of str, the compiler is forced to put it in memory somewhere so it can provide an address. It appears that the compiler created space for a on the stack first (or at least at a higher address), and then created space for str on the stack and copied the value from the register to the stack location.

You should not expect that inspecting the addresses of objects reveals or mirrors other aspects of a platform, such as its Application Binary Interface (which specifies, among other things, how function parameters are passed) or how stack is managed. A C implementation is free to rearrange things as long as the resulting program achieves the same observable behavior as defined by the C standard, and modern C implementations can make large and unexpected transformations while optimizing programs. Observable behavior includes defined outputs of a program but does not include any rules about the ordering of addresses of objects.

Incidentally, regarding your last question, yes, you are printing addresses incorrectly. To print an address, cast it to void * and print it with %p, not %X.

Upvotes: 3

Related Questions