tags:

views:

228

answers:

5
int main(void) {
    char *p = "hello";
    char *q = "world";
    *p = *q;
    printf("%s", *p);
}

I am trying to overwrite hello with world...

+11  A: 

Those string literals are stored in readonly memory, in the data section of your executable. You cannot (and should not try) to overwrite that memory.

Ed Swangren
There ya go, 10k.
GMan
And it's a misfeature of C (for legacy reasons) that string literals have type `char *` instead of `const char *`.
Steve Jessop
+5  A: 

This line:

*p = *q;

Will set the char (singular) pointed to by p to the char pointed to by q.

You want strncpy if you want to copy strings. (Although see Ed's comment about the read-only nature of the strings in your code).

geofftnz
For the record, `*cpy()` functions won't help here because the data is stored in read-only memory. But +1 for explaining the error in his logic.
Chris Lutz
Correct - I made the assumption that it was a basic pointer question. (Initially I didn't see the data section problem - C# has made me soft)
geofftnz
+10  A: 

You're just overwriting the first character of hello, i.e. h with the first character of world, i.e. w.

Also, if you want to stick with your original code,

p = q;
printf("%s", p);

Also, with p = q you are not overwriting anything. p now points to the first character of world.

As Ed said, you cannot overwrite the data stored in p with the data in q.

Jacob
A: 

char *p = "hello"; char *q = "world"; the both variables are constant, unchangeable

Macroideal
That's not true. The variables are not const, what they point to is.
Ed Swangren
Even that is not true. String literals in C are not constant (by type). They are simply non-modifiable. This is not exactly the same thing.
AndreyT
I meant the content p and q refer is constant, you cannot change the content
Macroideal
but you say that 'both *variables* are const', which is semantically meaningful in C. @Andrey: Yes, I was thinking more conceptually, but I should have said that they point to readonly memory.
Ed Swangren
+1  A: 

Firstly, your code only tries to overwrite the first character of "Hello" with first character of "World", i.e. it attempts to turn "Hello" into "Wello".

Secondly, you are trying to modify a string literal. Sitring litrerals are not modifiable. You can't "overwrite" string literal. Your attempt to overwrite "Hello" with "World" is not much different from an attempt to overwrite 5 with 8 by doing 5 = 8.

For further reading see http://stackoverflow.com/questions/1614723/why-is-this-c-code-causing-a-segmentation-fault/1614739#1614739

Thirdly, in order to print a string with printf you have to pass a pointer to the first character, not the first character itself. Your printf should look as printf("%s", p)

AndreyT