0

Possible Duplicate:
What is the difference between char a[] = “string”; and char *p = “string”;

char *str = "Hello";
printf("%c",++*str);

This gives segmentation fault on linux with gcc. The moment the first statement is changes to as

char str[10] = "Hello";

It works. What may be the reason?

Community
  • 1
  • 1

2 Answers2

3

It is undefined behaviour to attempt to modify a string literal.

The compiler is free to place it in read-only memory (as it probably does in your case). Attempting to modify read-only memory is what's probably triggering the segfault.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
-1

This statement char *str = "Hello"; stores the string "Hello" in RO-section and assigns the address of the area of RO-section(in which "Hello"is stored) to str. The data stored in RO-section cannot be modified thus you are getting a segfault.

char str[10] = "Hello";

is also wrong. You should instead write

char str[10];
strncpy(str,"Hello",sizeof(str));
glglgl
  • 89,107
  • 13
  • 149
  • 217
Manik Sidana
  • 2,005
  • 2
  • 18
  • 29
  • I cannot see how `char str[10] = "Hello";` is wrong. INO it is just perfext for this case. Well I would probably use `char str[] = "Hello";` but that doesn't make the given code wrong. – glglgl Jun 19 '12 at 09:38
  • I think its a bad idea to copy string this way. I am fine with char str[]="Hello" which lets compiler decide the size. However, the above practice char str[10]="Hello" can lead to segfault when say, a programmer changes/modifies the string. Lets say you have a code #define STR "Hello" and you are using char str[10] = STR; When, the programmer changes the macro STR to "HELLOWORLD!!!!" he mayget segfault. – Manik Sidana Jun 19 '12 at 09:42
  • `char str[10] = STR;` would copy the `#define`d `STR` into the `.data` segment, where it is perfectly modifiable. It won't definitely modify anything else. – glglgl Jun 19 '12 at 09:43
  • I was talking about the string copy/initialization for #defined case(Not implying printf("%c",++*str); modification). – Manik Sidana Jun 19 '12 at 09:45
  • Oh, yes! Now I got it. Yes, in this case you are right. Sorry for the confusion. In this case, the string isn't 0-terminated any longer, which makes using it dangerous. – glglgl Jun 19 '12 at 09:52
  • But be aware that the `strncpy()` solution is not as easy as it seems, as ["If there is no null byte in the first n bytes of the array pointed to by s2, the result is not null-terminated."](http://pubs.opengroup.org/onlinepubs/009695399/functions/strncpy.html) Instead, `strncpy(str,"Hello",sizeof(str)-1); str[sizeof(str)-1]='\0';` would be the way to go. – glglgl Jun 19 '12 at 09:54