-2

I found that main() allows overriding the argv[] parameters, because they are not const.

#include <cstdio>

int main(int argc, char** argv)
{
    printf("%i %s\n", argc, argv[1]);
    argv[1][0] = 'X';
    argv[1][4] = 'X';
    printf("%i %s\n", argc, argv[1]);
    return 0;
}

And below is the result. It compiled and worked.

Enter image description here

At first, I expected some program crush like undefined behaviour. However, it may make sense that I may want to have a program that accept sensitive data as parameter, but after I use it, I would like to override it it immediately. Is this is the only reason or there are others?

I would like to understand how this is working. I.e, where is the char** argv[] strings array located? How is it created and deleted? Etc.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anton K
  • 109
  • 6
  • `const` or not in the declared signature, what you're doing is undefined behavior. Stop. – πάντα ῥεῖ Jun 28 '22 at 19:38
  • 2
    The strings passed to your program are stored in locations by the Operating System; this is not a C++ thing. Before your program starts, the OS passes the quantity and location of the parameters passed to your program. The array of strings *should be* passed as a pointer to constant data, since many operating systems don't like your program parameters to be modified. Modifying your program's parameters is undefined behavior. – Thomas Matthews Jun 28 '22 at 19:40
  • πάντα ῥεῖ you mean in the tile of the page? it was a typo - fixed. – Anton K Jun 28 '22 at 19:52
  • The signature of `main` was strongly influenced by **C++**’s **C** heritage. – Eljay Jun 28 '22 at 21:52

1 Answers1

2

On Linux/x86-64, the argc, argv, and env parameters are stored on the call stack by the kernel doing the execve(2) according to ABI conventions.

See also this and the Linux Assembly HOWTO.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547