Because the string literal abc
is actually stored in a read-only area of the process and you are not supposed to modify it. The operating system has marked the corresponding pages as read-only and you get a runtime exception for an attempt to write there.
Whenever you assign a string literal to a char
pointer, always qualify it as const
to make the compiler warn you about such problems:
const char *c = "abc";
*c = 'd'; // the compiler will complain
If you really want to modify a string literal (although not directly itself, but its copy), I would suggest using strdup
:
char *c = strdup("abc");
*c = 'd'; // c is a copy of the literal and is stored on the heap
...
free(c);