1

Let's say I'm writing a C program which has:

int a = 1;
int b = 5;
int *p = &a;

Will:

int k = *(p+1);

always give k = 5?


Formally:

Is this "continuous" property of the variables' address on the stack implementation-dependant? If not, is anything guaranteed (for example &a < &b < &p)?

(This simple test using gcc on ubuntu gives k=5, but other tests involving different types do not work)

Paz
  • 737
  • 7
  • 22

1 Answers1

6

No... though it probably will on most platformsThere's absolutely no guarantee that your code will yield 5. What you have is undefined behaviour, which may result in your program craching. Never rely on undefined behaviour, full stop.

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • 2
    "though it probably will on most platforms"... I don't think so. Often, `b` won't even be put on the stack, but just be held in a register - depending on its usage. – glglgl Jan 27 '14 at 08:17
  • @glglgl: Fair point... will edit my answer. Just tried this code on my system, and got 5, too (slackware) – Elias Van Ootegem Jan 27 '14 at 08:19
  • 2
    And on more complex functions (where you run out of registers), the life time of variables often does not overlap so two variables can share the same address. – MSalters Jan 27 '14 at 08:20
  • 1
    @EliasVanOotegem ... depending on the optimization level. With `-O0`, you might get that result, with other levels, if unused, `b` will probably be optimized away. – glglgl Jan 27 '14 at 08:22
  • Stack alignment is another example for how this undefined behavior is completely unreliable: http://stackoverflow.com/questions/672461/what-is-stack-alignment – nitzanms Jan 27 '14 at 08:26