Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

gcc

elf

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?

like image 282
Marian Avatar asked Dec 02 '16 15:12

Marian


People also ask

Why is argc always 1?

As you can see, the first argument ( argv[0] ) is the name by which the program was called, in this case gcc . Thus, there will always be at least one argument to a program, and argc will always be at least 1.

How does argc work?

The first parameter, argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. The second parameter, argv (argument vector), is an array of pointers to arrays of character objects.

How does argc work in C?

The value of the argc argument is the number of command line arguments. The argv argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of argc counts this element.

What does int main int argc char * argv meaning?

argc stands for argument count and argv stands for argument values. These are variables passed to the main function when it starts executing. When we run a program we can give arguments to that program like − $ ./a.out hello.


1 Answers

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.

like image 140
Jean-Baptiste Yunès Avatar answered Sep 25 '22 23:09

Jean-Baptiste Yunès