int main(void) {
char *p = "hello";
char *q = "world";
*p = *q;
printf("%s", *p);
}
I am trying to overwrite hello with world...
int main(void) {
char *p = "hello";
char *q = "world";
*p = *q;
printf("%s", *p);
}
I am trying to overwrite hello with world...
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.
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).
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
.
char *p = "hello"; char *q = "world"; the both variables are constant, unchangeable
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)