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???

dsfa24
  • 41
  • 6

3 Answers3

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.

mvarshney
  • 364
  • 1
  • 8
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);
Havenard
  • 27,022
  • 5
  • 36
  • 62
0

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

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263