#include <stdio.h>
int main(int argc, char *argv[])
{
char* p = "Sam";
p[0] = 'R';
printf("%s\n",p);
return 0;
}
I ran it in windows which caused memory access violation error.
I know the string literals "Sam" is stored in the heap,which is static storage duration,but is it write-protected?
Thanks in advance!
No, it is not stored in the heap. Where did you find it in? Burn that book.
It is stored in the read-only data segment of the program. Of course, whether you get violation error or not is strictly OS/hardware dependent.
Also note that char* p = "Sam";should be a compiler error for this very reason (it should have to be a constchar*). Unfortunately, some compilers allow this to slide without generating an error.
so,actually it is not stored in heap,oh my god,it totally confuses me.
on the other hand,it is unforgivable for the compiler not to generate such trivial error.Really bad design.
Thanks for the advice.
Don't listen the troll, it said the very same thing some time ago. The C++ standard says very clearly: An ordinary string literal has type “array of n const char”