codeponderer
codeponderer

Reputation: 55

Extending argv to hold more values

This is mostly out of curiosity.

In the ISO C specification the following is said:

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.

http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1425.pdf section 5.1.2.2.1 Program startup

Still, I have seen recommendations online that you shouldn't reallocate argv to extend it, but rather copy it.

Is there a specific reason to not extend argv that doesn't affect other char** or is this by convention?

I don't know if there is any real need for extending argv with additional values, but the question is whether argv is special from the POV of the program.

Upvotes: 3

Views: 1124

Answers (1)

OfNothing
OfNothing

Reputation: 600

There is nothing special about argc and argv as parameters.

1) argc is just an int that is passed by copy into the main function. changing it has absolutely no affect on anything.

2) argv, is just an array of pointers to c-strings. The standard lets you modify the strings pointed to by argv.

Note that the standard does not let you free the strings pointed to by argv nor does it say you are allowed to modify the array pointed to by argv.

For example, if argc==2 and argv[1] points to a string "hello world", this would be fine:

argv[1][0]='c'; // the string is now "cello world" which is the name of a store
                // located right next to banjo emporium.

but it is undefined to do:

argv[1] = "yo mamma"; // what are you thinking, are you 12 ???

Although, nothing bad happens if you do that -- it is just not defined. A test on centos 6.5 with gcc 4.4 (Don't make fun of me for using such an old version, okay?) gave me no issues. So nobody is trying to free() the contents of argv on program exit. Also there are several libraries that as a side effect of processing argv, reorder its contents. I cannot think of where I saw that though.

However, what you cannot do, because you have no way to do it, is to change the size of the array pointed to by argv. For example, on my system, trying to realloc() argv throws an invalid pointer error. In other words, the array pointed to by argv, does not appear to be located on the heap.

Not being able to realloc() arrays passed into your functions is nothing new or special, for example the array might be static, or allocated on the stack, and the standard says nothing about how the argv array is allocated.

In any case, the standard allows the programmer to use the strings passed into main in any way without fear that they will be modified by somebody else, but it does not explicitly let the programmer change the array that holds the strings.

Upvotes: 6

Related Questions