考虑这段代码片段:
char *str = "hellow Ghost";
str[0] = 'z';
printf("%s", str);
这是一个段错误。它还会出现运行时内存错误吗?
我对段错误的理解是:当您访问不属于您的内存时出现段错误。它基本上是一个为您创建的实用程序,旨在简化您的工作,而不会让您损坏内存。
段错误涵盖了多少和何种类型的内存错误,以及什么调用它来检查指针或引用在处理内存时是否错误。
由于逻辑不正确,也会出现运行时错误。除此之外,关于内存的运行时错误和段错误之间是否有任何区别?
最佳答案
It is a segmentation fault. Also does it come under run time memory error ?
严格来说,这是一种未定义的行为。您可能会也可能不会出现段错误。什么事情都可能发生。
声明
char *str = "hellow Ghost";
相当于
char const *str = "hellow Ghost";
字符串文字存储在只读部分中,任何修改它的尝试都会调用 UB。
C11:J.2 未定义行为:
The behavior is undefined in the following circumstances:
...
— The program attempts to modify a string literal (6.4.5).
关于c++ - "Segmentation fault"与 "run time"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24663363/