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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-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));

6 Comments

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.
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.
char str[10] = STR; would copy the #defined STR into the .data segment, where it is perfectly modifiable. It won't definitely modify anything else.
I was talking about the string copy/initialization for #defined case(Not implying printf("%c",++*str); modification).
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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.