分段错误和运行时错误

发布于 2024-12-02 17:49:43 字数 477 浏览 1 评论 0原文

可能的重复:
修改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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

翻身的咸鱼 2024-12-09 17:49:43

字符串文字实际上是 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 a char*. That does not mean you are really allowed to modify them.

心不设防 2024-12-09 17:49:43

你的错误不能在编译时显现出来;在那里,你的两种说法都是完全有效的。在运行时,字符串 "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.

玩心态 2024-12-09 17:49:43
char *p="Hello";

类型的表达式被视为已弃用"Hello" 是存储在只读存储区域中的字符串文字;尝试修改这些位置是未定义行为。在好的平台中,它会导致崩溃/分段错误

它们被表示为,

const char *p = "Hello";

这意味着p不允许被修改。如果您想让 p 可修改,则将其声明为,

char p[] = "Hello";  // 'p' is an array of size 6
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文