Marian
Marian

Reputation: 7482

Why is the address of argc different at each run of program?

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?

Upvotes: 7

Views: 295

Answers (1)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36441

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.

Upvotes: 14

Related Questions