Possible Duplicate:
Modifying value of char pointer in c produces segfault
This is a piece of code ...
void main()
{
char *p="Hello";
*p= 'h'; // Segmentation fault .
}
I understand the fact that there is a segmentation fault and it gives me a run time error also .But I wonder , why is it a RUN TIME ERROR ?? Why cant the compiler tell me before executing the program ? Why does not it show a COMPILE TIME ERROR ?
PS : I use Visual C++ 2005 Express ..
String literals are really of type char const*
. However, for compatibility with older C code that's not const-correct, C++ allows them to be assigned to a char*
. That does not mean you are really allowed to modify them.
Your fault cannot manifest itself at compile time; there, both your statements are completely valid. It is at runtime when the string "Hello"
is read-only and you're trying to modify it.
char *p="Hello";
type of expressions are considered deprecated. "Hello"
is a string literal stored in a read only memory area; attempting to modify those locations is an Undefined Behavior. In good platforms it results in a crash / segmentation fault
They are expressed as,
const char *p = "Hello";
which means that p
is not allowed to be modified. If you want to let p
be modifiable then declare it as,
char p[] = "Hello"; // 'p' is an array of size 6
精彩评论