0

I have this part in a code:

char* data="My name is: ";

I would like to add to this the argv[1] argument with represents a name. How to do this in c code? I've tried strcpy and strcat but i have segmentation fault when Ipcp do this:

strcpy(data,argv[1]);

Can anyone please help?

Also why this: data=data+argv[1] is not working?

Mike Weller
  • 45,401
  • 15
  • 131
  • 151
just ME
  • 1,817
  • 6
  • 32
  • 53
  • 3
    You **must not** modify a string literal. Copy it first in your own buffer and then modify it to append the new data.Good Read: [What is the difference between char a\[\] = “string”; and char *p = “string”;](http://stackoverflow.com/questions/9460260/what-is-the-difference-between-char-a-string-and-char-p-string) – Alok Save Sep 11 '12 at 10:21

4 Answers4

4

You need to provide some memory, where the result of the concatentation can be stored into. For example:

char buffer[1024];

strcpy(buffer, "My name is: ");
strcat(buffer, argv[1]);

Note, however, that this is error prone: if the value of argv[1] combined with the prefix string is longer than 1024 characters, this produces a buffer overflow. So, maybe something like this:

char* prefix = "My name is: ";
int length = strlen(prefix) + strlen(argv[1]) + 1;
char* buffer = malloc(length);

if (!buffer) abort();
else 
{
    strcpy(buffer, prefix);
    strcat(buffer, argv[1]);

    /* Do something with buffer here. And don't
     * forget to free it, once you no longer need
     * it. This is C -- no garbage collection. */

    free(buffer);
}
Dirk
  • 30,623
  • 8
  • 82
  • 102
0

Memory for data will be allocated in read-only section. so modifying will cause issue.

where in memory are string literals ? stack / heap?

+ operator will not do concat as you thought.

strcat() function is implemented in string.h.

Community
  • 1
  • 1
Jeyaram
  • 9,158
  • 7
  • 41
  • 63
0

Also why this: data=data+argv[1] is not working?

About this one - in C data and argv are nothing more than pointers to address in the memory containing your string. You can't concatenate strings(char*) this way. I suggest to take a look at the string library and maybe a bit more in C as a whole.

0

You cant append to th data pointer because there are no space in it

char result_data [1024];
char* data="My name is: ";
strcat(result_data, data);
strcat(result_data, argv[1]);
Chandra Sekhar
  • 16,256
  • 10
  • 67
  • 90
AGo
  • 284
  • 2
  • 6