2
#include<stdio.h>
#include<string.h>
int main(int argc,char *argv[])
{
    char string[]="#";
    printf("%s\n",argv[1]);
    printf("%s\n",argv[2]);
    printf("%s\n",argv[3]);
    strcat(argv[1],string);
    printf("argv[1] is %s\n",argv[1]);
    printf("argv[2] is %s\n",argv[2]);
    printf("argv[3] is %s\n",argv[3]);
    return 0;
}

when I use strcat() to add something to the end of the argv[1],argv[2] will be lost( strlen(argv[2]) changes to 0 after use strcat ).But argv[3] has no change .Why???

3
  • What is this code doing o.O' Commented Apr 10, 2013 at 2:31
  • possibly duplicate of stackoverflow.com/questions/963493/… Commented Apr 10, 2013 at 2:35
  • @Thomas This code is just to solve my question with argv[].It can do nothing meaningful. Commented Apr 10, 2013 at 3:18

3 Answers 3

2

You cannot append stuff directly to argv[] because each argv[] is allocated serialized and to a space in memory that can only hold its original size.

To understand what is happening, imagine argv is something like this:

char buffer[] = "./program\0one\0two\0three\0";
char *argv[4] = { &buffer[0], &buffer[10], &buffer[14], &buffer[18] };

So as you can see, if you write something after "one" you will overwrite "two" and break the whole thing because they are serialized in memory.

To workaround this, you have to copy each argv[] to a bigger buffer where you can safely make the modifications. For instance:

char buf[1024];
strcpy(buf, argv[1]);
strcat(buf, string);
printf("argv[1] is %s\n", buf);
Sign up to request clarification or add additional context in comments.

Comments

2

Remember that "strings" in C are zero terminated arrays of characters. Suppose the original four arguments were "one", "two", "three" and "four"; then these four arguments are stored in memory as

one\0two\0three\0four\0

when you appended # after the argv[1] (strcat will add a \0 also), the memory content becomes:

one\0two#\0hree\0four\0

you can now verify that argv[2] points to the \0 char, hence it is a empty string. argv[3] still points correctly, and it remains intact.

Comments

0

You aren't supposed to modify argv[] = the effects are undefined

4 Comments

I think so too, but is there any reference?
Actually, you can modify argv[whatever] (the pointer). Modifying what the pointer points to is not so kosher.
@paxdiablo: So, is it like char const * argv[]?
No it's not necessarily const - the standard doesn't say what it has to be. Just that the memory isn't yours so you shouldn't change it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.