分段错误和运行时错误
可能的重复:
修改c中char指针的值会产生段错误 < /p>
是一段代码...
void main()
{
char *p="Hello";
*p= 'h'; // Segmentation fault .
}
我知道存在分段错误,它也给了我一个运行时错误。但我想知道,为什么它是一个运行时错误?为什么编译器不能在执行程序之前告诉我?为什么它不显示编译时间错误?
PS:我使用 Visual C++ 2005 Express ..
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 ..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
字符串文字实际上是 char const* 类型。但是,为了与 const 不正确的旧版 C 代码兼容,C++ 允许将它们分配给
char*
。这并不意味着您真的可以修改它们。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 achar*
. That does not mean you are really allowed to modify them.你的错误不能在编译时显现出来;在那里,你的两种说法都是完全有效的。在运行时,字符串
"Hello"
是只读的,而您正尝试修改它。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.类型的表达式被视为已弃用。
"Hello"
是存储在只读存储区域中的字符串文字;尝试修改这些位置是未定义行为。在好的平台中,它会导致崩溃/分段错误它们被表示为,
这意味着
p
不允许被修改。如果您想让p
可修改,则将其声明为,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 faultThey are expressed as,
which means that
p
is not allowed to be modified. If you want to letp
be modifiable then declare it as,