After reading Is argv[n] writable?, I'm not completely certain what conclusions to take from the thread.
The C standard, from C89 onwards, states:
The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.
In a program, I've been testing the following code:
int main(int argc, char *argv[])
{
int i;
for (i = 1; i < argc; i++)
{
/* Do something */
argv[i] = NULL; /* argv[i] is no longer needed */
}
for (i = 1; i < argc; i++)
{
if (argv[i])
/* Do something else */
}
}
While this works for me on Linx Mint 17.2 with gcc 4.8.4, setting argv[i] = NULL seems to be both valid and non-standardized behaviour, at least according to the standard. This makes me reluctant to use this code in production.
(I'm basically iterating over argv twice, making sure I skip argv[i] == NULL.)
What kind of evidence, if any, is there to support re-assigning
argv[i]in this way? I'm concerned I might cause memory and/or compiler problems, as I can't guarantee how other systems will handle this.Is there a better method to do what I want to do?
EDIT
I forgot to add that the input args consist of flags and filenames. These can be in any order, so I'm using argv[i] = NULL to help me identify filenames. - and / are valid for filenames and flags.
EDIT 2
The standard talks about argv and the strings pointed to by the argv array. Those can be modified. But what about the pointers themselves. Does the standard explicitly say they can be modified? Or am I misinterpreting the standard?