7

Today I came across the following situation. I run several times the following program:

#include <stdio.h>
int main(int argc, char **argv) {
  printf("%p\n", &argc);
}

On an Intel i7 with linux and gcc compiler, this program gives different output at each run:

i7:~/tmp$ gcc t.c 
i7:~/tmp$ ./a.out 
0x7fffc127636c
i7:~/tmp$ ./a.out 
0x7fffdefed97c
i7:~/tmp$ ./a.out 
0x7fff7f32454c

I would expect that developers of linux, elf, gcc or whatever is related would try to ensure that the stack is positioned on the same address at each invocation of a program. It would facilitate tracing and fixing of strange bugs which may happen when dealing with pointers and addresses of variables (similarly as virtual addresses are better for fixing bugs compared to physical addresses).

I wonder why the stack is mapped to different addresses at each invocation of the program?

Marian
  • 7,402
  • 2
  • 22
  • 34
  • 11
    https://en.wikipedia.org/wiki/Address_space_layout_randomization? – dbrank0 Dec 02 '16 at 15:06
  • 2
    OT: It has to be `printf("%p\n", (void*) &argc);`, BTW. The conversion specifier `p` is defined for `void`-pointers only. – alk Dec 02 '16 at 15:10
  • 2
    Related: http://stackoverflow.com/questions/11238457/disable-and-re-enable-address-space-layout-randomization-only-for-myself – alk Dec 02 '16 at 15:16

1 Answers1

14

This is for security reasons, so that an attacker could not be able to make too many assumptions on exact memory layout of variables, functions,...

Let me encourage you to read things about «buffer overflow attacks» (one of the possible causes) and «ASLR» (Address Space Layout Randomization) one of the possible preventive partial curation.

So it is the case that the compiler generates fixed addresses, but the runtime changes some of the things...

If you want to change that behavior, see disable ASLR in Linux for example.

Community
  • 1
  • 1
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69