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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With