c++cparametersprogram-entry-pointargv

Where are the the argv strings of the main function's parameters located?


In C/C++, the main function receives parameters which are of type char*.

int main(int argc, char* argv[]){
  return 0;
}

argv is an array of char*, and points to strings. Where are these string located? Are they on the heap, stack, or somewhere else?


Solution

  • 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.