Where are C/C++ main function's parameters? Where are C/C++ main function's parameters? c c

Where are C/C++ main function's parameters?


They are compiler magic, and implementation-dependent.


Here's what the C standard (n1256) says:

5.1.2.2.1 Program startup
...
2 If they are declared, the parameters to the main function shall obey the followingconstraints:

  • The value of argc shall be nonnegative.

  • argv[argc] shall be a null pointer.

  • If the value of argc is greater than zero, the array members argv[0] throughargv[argc-1] inclusive shall contain pointers to strings, which are givenimplementation-defined values by the host environment prior to program startup. Theintent is to supply to the program information determined prior to program startupfrom elsewhere in the hosted environment. If the host environment is not capable ofsupplying strings with letters in both uppercase and lowercase, the implementationshall ensure that the strings are received in lowercase.

  • If the value of argc is greater than zero, the string pointed to by argv[0]represents the program name; argv[0][0] shall be the null character if theprogram name is not available from the host environment. If the value of argc isgreater than one, the strings pointed to by argv[1] through argv[argc-1]represent the program parameters.

  • The parameters argc and argv and the strings pointed to by the argv array shallbe modifiable by the program, and retain their last-stored values between programstartup and program termination.

The last bullet is the most interesting wrt where the string values are stored. It doesn't specify heap or stack, but it does require that the strings be writable and have static extent, which places some limits on where the string contents may be located. As others have said, the exact details will depend on the implementation.


It's actually a combination of compiler dependence and operating system dependence. main() is a function just like any other C function, so the location of the two parameters argc and argv will follow standard for the compiler on the platform. e.g. for most C compilers targeting x86 they will be on the stack just above the return address and the saved base pointer (the stack grows downwards, remember). On x86_64 parameters are passed in registers, so argc will be in %edi and argv will be in %rsi. Code in the main function generated by the compiler then copies them to the stack, and that is where later references point. This is so the registers can be used for function calls from main.

The block of char*s that argv points to and the actual sequences of characters could be anywhere. They will start in some operating system defined location and may be copied by the pre-amble code that the linker generates to the stack or somewhere else. You'll have to look at the code for exec() and the assembler pre-amble generated by the linker to find out.