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...
Attempting to modify a string literal results in undefined behavior. For example, some implementations will store that string in a read-only section of memory. You cannot (and should not try) to overwrite that memory.
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
.
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).
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 Why is this string reversal C code causing a segmentation fault?
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)
You are not passing the address of the pointer if you want to print the "world" then you need to pass the address of the string world to the pointer "hello" this is achieved by writing p=q;
.
Problem solved. The rest of the code is correct.
char *p = "hello"; char *q = "world"; the both variables are constant, unchangeable
Both are L values so can't b changed..... leads to Segmentation Fault or any Runtime Logical error
so it is safe to use
p=q;
as now p starts pointing to the string to which q is pointing