c++ - "Segmentation fault"与 "run time"错误?

标签 c++ c memory segmentation-fault runtime

考虑这段代码片段:

  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/

相关文章:

java - 使用 Java 读取非常大的文件

c++ - 当我输入 0 时,我收到消息 "0 has already been entered"6 次

c++ - new 运算符在汇编中返回什么?

c - 为什么在获取整数作为输入时不需要 getchar() ?

c - 父进程和子进程的内存映射文件问题

c++ - 我可以在 MacBook Pro 上分配的最大内存量是多少?

C++ 十六进制解析

c++ - 防止实例化未使用的默认函数参数

c - 错误 : expected ')' before ';' token

C sha1 实现不适用于 Unix