user1462787
user1462787

Reputation: 669

Understanding addresses in C

For some structure splab:

int main() {

   int a;
   struct splab *s1;
   int b;

   printf("%x\n",&a);
   printf("%x\n",&b);

   return 0;
 }

I think I should get in the second print: bfc251e8 - 8 (i.e. account for the space occupied by s1).

Instead, I got:

bfc251e8
bfc251ec

Why?

Upvotes: 2

Views: 166

Answers (3)

ArjunShankar
ArjunShankar

Reputation: 23670

It's not just really about the order of the variables. You never use s1 and the compiler can (and may) simply optimize it away and not allocate space on the stack.

Here is what I get if I try to print only the addresses of a and b, like you do:

ffeb7448 (&a)
ffeb7444 (&b)

i.e. 4 bytes difference.

Here is what I get if I try to print the address of s1 also (and therefore end up using the declaration s1):

ffe109cc (&a)
ffe109c8 (&s1)
ffe109c4 (&b)

You can see that it does in fact lie in between a and b this time (and it need not always, as other answers already point out), and that a and b are separated by 8 bytes instead of 4.


Another slightly related point has to do with alignment:

For example:

struct foo
{
  int a;
  char b;
};

While this struct looks like it might be 5 bytes wide on a machine with 4 byte integers, my compiler says, sizeof (struct foo) == 8.

This is so that foo is always aligned at 8 byte boundaries (this includes use of struct foo local variables).

e.g.

int bar (void)
{
  struct foo a;
  struct foo b;

  /* Do some work.  */
}

Here, a and b are separated by 8 bytes on my machine's compiler, even though each foo only really ever uses 5 bytes.

All this goes to show is: Never assume anything related to widths, alignment, relative position, etc. when writing code.

Upvotes: 5

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43498

The compiler is free to reorder the location of the variables on the stack, so it is possible that the b variable comes before the s1 pointer, although the latter is declared in the middle.

Such rearrangements might enable better memory utilisation due to some data types requiring alignment, therefore eliminating any possible gaps.

Upvotes: 2

Levon
Levon

Reputation: 143047

Are you saying because the pointer s1 was allocated between a and b the addresses needed to vary by the amount the pointer uses memory? (It wasn't quite clear to me).

If so, I don't think you can count on this, how memory is allocated between different variables is not under your control. It may appear that memory is allocated in a linear fashion, but it's not something that you can rely on.

If I'm wrong interpreting your question/could you please rephrase/clarify it?

Upvotes: 1

Related Questions