4

It is known the prototype for main funcion in C is int main(int argc, char **argv). Where do those strings pointed by argv array reside? Which memory segment are they in? Data, stack or heap?

Thanks.

Sean
  • 2,649
  • 3
  • 21
  • 27
  • Perhaps this will help. http://stackoverflow.com/questions/14588767/where-in-memory-are-my-variables-stored-in-c – IT_User Jan 29 '16 at 00:06
  • 2
    @kaylum: The purported duplicate asks at the level of the C language, for which the only answer is "implementation-defined". Here note the [tag:linux] tag: it is about a specific implementation. – Nate Eldredge Jan 29 '16 at 00:24

1 Answers1

5

Under Linux they are on the stack when the program starts, both the pointers themselves and the strings they point to. This will be somewhere up above main()'s stack frame. The C library startup code takes care of passing an appropriate pointer to main().

You can find the kernel code that sets up a new program's stack, including arguments and everything else, in fs/binfmt_elf.c, in the function create_elf_tables().

(Fun fact I just learned: further up on the stack you can find 16 random bytes, placed there at exec time by the kernel, for your RNG-seeding convenience. Just in case you don't want to go to the trouble of opening /dev/urandom.)

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
  • Further up? Does this mean that main() could have more than three arguments so you can reach those bytes? If so, what would the prototype be? If not, how do you reach those bytes? – mcleod_ideafix Jan 29 '16 at 00:27
  • 1
    You, the user, are not supposed to reach them. The C library startup code would have access to them, since they are at a known offset from the bottom of the stack (`%rsp`) when the program's execution starts. And it could, for example, call `srand()` using them. But unless you have intimate familiarity with what the C startup code does, or unless it makes those bytes available somehow (I don't know if it does), your code won't have a good way to know where they are. – Nate Eldredge Jan 29 '16 at 00:30
  • actually, `main()` does have an optional 3 argument. a pointer to the environment. However, that third argument is rarely if ever used. – user3629249 Jan 30 '16 at 18:08