Title: Why is argument three equal to "TERM_PROGRAM=Apple_Terminal"?
Tags: c;macos;arguments
Question: I am making assembly code which is the equivalent to
#include <stdio.h&gt;
int main(int argc, char *args[]){
printf("%s", args[0]);
printf("%s", args[1]);
printf("%s", args[2]);
return 0;
Both the c code and assembly display the following results:
$ ./main:
./main(null)TERM_PROGRAM=Apple_Terminal
$ ./main one:
./mainone(null)
$ ./main one two:
./mainonetwo
When executing ./main one and ./main two, the output makes sense. However, why does calling ./main with no arguments show the third argument as being TERM_PROGRAM=Apple_Terminal?
The strange thing is when I make a bash script that executes:
echo $0
echo $1
echo $2
I get the following output when I can ./main with no arguments:
./main
<empty line&gt;
<empty line&gt;
Where <empty line&gt; is a empty line.

Here is the accepted answer: Strictly speaking, accessing argv beyond argc is an undefined behavior. In your case, keep in mind that the main signature is (int args, char ** argv, char ** envp). The last argument points to the program environment, and it's just happen that the environment strings are immediately adjacent in memory to the program arguments.
Comment for this answer: So in terms of the stack, the environment variables are pushed onto the stack first, arguments next and then the argument count? Or the other way round. Still figuring out how the stack works.
Comment for this answer: @iProgram: The arguments and the environment variables may not be on the stack at all, and you should not be concerned about whether they are or not. At some point while your program was being initialized, some software arranged for copies of the arguments and the environment variables to be stored inside the memory set up for your process. That might have been done by the loader that initially runs your program or by some software inside your process that helps initializes the C environment, possibly with help from the operating system.…
Comment for this answer: … It might have put those copies on the stack or somewhere else. What you discovered as that the environment variables seem, in at least one case, to follow the arguments in memory. They could follow them in the memory that is the stack, or they could follow them in memory that was otherwise allocated for them. Either of those would get the same behavior in this case. We do not know.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:09/29/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c><macos><arguments>', 'Title': 'Why is argument three equal to "TERM_PROGRAM=Apple_Terminal"?', 'ViewCount': 206, 'id': 52571747, 'user_AboutMe': None, 'user_AccountId': 4348356.0, 'user_DisplayName': 'iProgram', 'user_Reputation': 5577.0, 'user_Views': 417.0, 'user_id': 3549629.0}}