char** key;
strcpy(*key, "Hello");
strcpy(*(key+1), "World");
printf("%s", *key);
The second strcpy
has no error, while the first strcpy
has a segmentation fault. How should I modify to achieve the original purpose?
char** key;
strcpy(*key, "Hello");
strcpy(*(key+1), "World");
printf("%s", *key);
The second strcpy
has no error, while the first strcpy
has a segmentation fault. How should I modify to achieve the original purpose?
What you are doing is Undefined Behavior.
char * strcpy ( char * destination, const char * source )
strcpy expects a destination which can be modified. You are passing a char **
which is causing the problem since you have not allocated any memory for it to write to.
This is what (perhaps) you were trying:
char* key = malloc(sizeof(char)*7); // 7 because it can Hold World with a Nul character
strcpy(key, "Hello");
strcpy((key+1), "World");
printf("%s", key);
It is not clear in your code whether you are allocating any buffer for key. I believe that's why you are getting SEG fault.
You must allocate memory to before you do strcpy()
, if you want to skip allocating memory try strdup()
.
To simplify, not sure you really want char **key
, doing with char *key
char* key = malloc(sizeof(char) * 100); //allocate to store 100 chars
strcpy(key, "Hello");
strcpy(key + strlen(key), "World");
//or strcat(key, "World");
the second strcpy has no error, while the first strcpy has a segmentation fault
How do you know 2nd one does not have error when it never executed because of segmentation fault?
No memory has been allocated for key
. You can allocate memory using malloc
before the first strcpy
.
*key = malloc(32 * sizeof(char)); // pick a size of buffer
I suspect the second call will also cause a segfault. It's (probably) going to be writing into unallocated space.