Search code examples
cstringcommand-line-argumentsargv

Are the strings in argv modifiable?


I just wrote a small program that reads command line arguments in C, nothing too difficult. I was also modifying them, for example changing the first character of the parameter to uppercase.

I know that you shouldn't modify string literals as it can cause undefined behavior, so was just wondering if the strings in the *argv[] are literals that you shouldn't change.

int main(int argc, char *argv[])

Solution

  • From the C11 standard draft N1570, §5.1.2.2.1/2:

    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.

    They are modifiable. That means they are not string literals.

    But be careful: the upper citation only refers to pointers to strings, excluding the obligatory null pointer at argv[argc]1.
    From the C11 standard draft N1570, §5.1.2.2.1/2 (same as above)1:

    argv[argc] shall be a null pointer


    Notes:

    • Something regarding this sentence:

      I know that you shouldn't modify string literals as it can cause undefined behavior [...]

      "can"? It does always. Undefined behavior includes expected, as if well-defined, and unexpected behavior.


    1 Thanks to @black!