开发者

Segmentation fault and run time error [duplicate]

开发者 https://www.devze.com 2023-04-01 06:13 出处:网络
This question already has answers here:开发者_运维知识库 Closed 11 years ago. Possible Duplicate:
This question already has answers here: 开发者_运维知识库 Closed 11 years ago.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号