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

Yu Hao
  • 115,525
  • 42
  • 225
  • 281
Song Zhibo
  • 39
  • 1
  • 4
  • 3
    Uh. Is this the whole of your code? You haven't initialized key to point to anything. So its an uninitialized pointer that you are dereferencing to char* to pass to strcpy. – kfsone Oct 09 '13 at 05:50

4 Answers4

1

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);
Sadique
  • 22,181
  • 7
  • 62
  • 90
1

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.

Santanu C
  • 1,302
  • 3
  • 19
  • 36
0

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?

Rohan
  • 50,238
  • 11
  • 84
  • 85
0

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.

Steve
  • 7,051
  • 2
  • 28
  • 52