Is string literals write-protected ?

Hi all:
Please see the code below:
1
2
3
4
5
6
7
8
#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!
closed account (EzwRko23)
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.
Last edited on
Also note that char* p = "Sam"; should be a compiler error for this very reason (it should have to be a const char*). Unfortunately, some compilers allow this to slide without generating an error.
closed account (EzwRko23)
Unfortunately, some compilers allow this to slide without generating an error.

These are not faulty compilers, but faulty ISO/ANSI C++ standard.
Last edited on
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.
These are not faulty compilers, but faulty ISO/ANSI C++ standard.


I thought the standard said they had to be const char*?

At the very least compilers should generate a high level warning.
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
Topic archived. No new replies allowed.