I was looking at the code for the GNU coreutils package, specifically the program 'yes', when I saw this block of code in the main
function (line 78):
if (argc <= optind)
{
optind = argc;
argv[argc++] = bad_cast ("y");
}
How can the array argv
be expanded this way? Obviously, just taking any code snippet out of context is a really bad idea, so I looked to see if argv
is modified at all beforehand, and it doesn't seem to be except in a call to initialize_main (&argc, &argv)
, which doesn't seem like it takes an argument for a "new size" or anything like that (but in C, like any language, things aren't always what they seem to be).
I decided to write a simple program to test if I could call realloc()
on argv
char** new_argv = realloc(argv, ++argc * sizeof*argv);
And it worked (with VS2013 on Windows 10). It returned a pointer to the allocated memory. Of course, that doesn't actually mean anything if it's undefined behavior.
So, long story short, my question is, how is argv
allocated? Is it actually safe to realloc argv
?
argv
is an array of pointers tochar
(owned by the program), the last one, i.e.argv[argc]
is supposed to be a null pointer, so it can be made to point to something else. – Radiothermy