-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Would the following program give the same output at all times
int main(int argc, char *argv[])
{
strcpy(argv[0], "Hello");
strcpy(argv[1],"Good Morning");
printf("%s\n%s\n",argv[0],argv[1]);
return 0;
}
Beyond Richard Bos' reply wrt the number of arguments, there are other
'undefined behaviours' in this code that could cause it to vary it's output.
Each argv[] is a pointer to either NULL (in the case of argv[argc]) or a
string. Let us ignore the special case of argv[argc] for the moment.
The string that the argv[n] pointer points to is only guaranteed to be
as long as necessary to store the passed argument. This /can/ be smaller
than the strings you write into the storage (you are using strcpy(), you
are writing strings, not copying pointers).
So, if argv[0] pointed to a two character array (like "a"), then your
strcpy(argv[0], "Hello");
replaces those two characters, then promptly goes out-of-bounds and
invokes undefined behaviour. Similar behaviour comes from your
strcpy(argv[1], "Good Morning");
statement.
Since argc and argv[] reflect external values, supplied (somehow) prior
to the initiation of your program, you have no programmatic control over
their content (at least, not in /this/ program), and can (and will) vary
depending on external circumstances.
In other words, at 09:00, your program may be invoked with
argc == 2
argv[0] -> "a"
argv[1] -> "b"
argv[2] == NULL
while at 09:03, your program is invoked with
argc == 1
argv[0] -> "some program Name"
argv[1] == NULL
and at 09:05, your program is invoked with
argc == 3
argv[0] -> "a big program name"
argv[1] -> "something much larger than I need"
argv[2] -> ""
argv[3] == NULL
And, /that/ is time-variant undefined behaviour.
- --
Lew Pitcher, IT Specialist, Enterprise Data Systems
Enterprise Technology Solutions, TD Bank Financial Group
(Opinions expressed here are my own, not my employer's)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (MingW32)
iD8DBQFC+LLxagVFX4UWr64RAr5LAKC6bz9iGVC5IBcn1nQ4kSCxsTHqLgCeMk35
NDJu9FtCPmm6cEov1zkK+e4=
=S06b
-----END PGP SIGNATURE-----