I am learning pointers in C. When I declare :
char c1[] ="hello";
c1[0] = c1[1];
printf("%s\n", c1);
It prints out eello
But when I do the following:
char * c2="hello";
c2[0] = c2[1];
printf("%s\n", c2);
it compiles in C# but the program crashes. Could you help me clarify what happens in the Stack when I execute the program?
In this line of code,
c1
is declared as a local array ofchar
s - and its contents will be placed on the stack of the function. Function stacks are modifiable and soc1[0] = ...
will work.there's a subtle difference here -
c2
is not an array, but a pointer to a string literal. Modifying it is undefined behavior per the standard - in practice, what usually happens is that the"hello"
string gets placed in the executable's read-only.data
section - and attempting to modify it triggers a page fault that crashes the program.