3

Why does the following happen:

char s[2] = "a";
strcpy(s,"b");
printf("%s",s);

--> executed without problem

char *s = "a";
strcpy(s,"b");
printf("%s",s);

--> segfault

Shouldn't the second variation also allocate 2 bytes of memory for s and thus have enough memory to copy "b" there?

erikbstack
  • 12,878
  • 21
  • 81
  • 115

3 Answers3

12
char *s = "a";

The pointer s is pointing to the string literal "a". Trying to write to this has undefined behaviour, as on many systems string literals live in a read-only part of the program.

It is an accident of history that string literals are of type char[N] rather than const char[N] which would make it much clearer.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
  • 2
    String literals are of type `char[N]`, where N is the length of the literal including nul terminator. But yes, it should be `const char[N]`, and indeed it is in C++, which is stricter than C about const-correctness. – Steve Jessop Jun 12 '12 at 09:59
5

Shouldn't the second variation also allocate 2 bytes of memory for s and thus have enough memory to copy "b" there?

No, char *s is pointing to a static memory address containing the string "a" (writing to that location results in the segfault you are experiencing) whereas char s[2]; itself provides the space required for the string.

If you want to manually allocate the space for your string you can use dynamic allocation:

char *s = strdup("a"); /* or malloc(sizeof(char)*2); */
strcpy(s,"b");
printf("%s",s); /* should work fine */

Don't forget to free() your string afterwards.

Constantinius
  • 34,183
  • 8
  • 77
  • 85
1

Altogather a different way/answer : I think the mistake is that you are not creating a variable the pointer has to point to and hence the seg fault.

A rule which I follow : Declaring a pointer variable will not create the type of variable, it points at. It creates a pointer variable. So in case you are pointing to a string buffer you need to specify the character array and a buffer pointer and point to the address of the character array.

Shash
  • 4,160
  • 8
  • 43
  • 67