“分段错误"vs“运行时间"错误?

2022-01-12 00:00:00 memory c runtime segmentation-fault c++

考虑一下这段代码:

  char *str = "hellow Ghost";
  str[0] = 'z';
  printf("%s", str);

这是一个分段错误.是否也会出现运行时内存错误?

It is a segmentation fault. Also does it come under run time memory error ?

我对分段错误的理解是:当您访问不属于您的内存时出现分段错误.它基本上是为您创建的实用程序,可以在不破坏内存的情况下简化您的工作.

What I understood by segmentation fault is : Segmentation fault when you are accessing a memory that doesn't belong to you. It is basically a utility created for you to ease your work without letting you corrupt the memory.

分段错误涵盖了多少和什么样的内存错误,以及调用它以检查指针或引用在处理内存时是否错误.

How much and what kind of memory errors Segmentation fault covers and what invokes it to check out that a pointer or reference is wrong dealing with memory.

运行时错误也会由于不正确的逻辑而发生.除此之外,关于内存的运行时错误和分段错误之间是否有任何区别.

Run time error also occurs due to improper logic. Apart from that, are there any differences between run time error and segmentation fault regarding memory.

推荐答案

这是一个分段错误.它也属于运行时内存错误吗?

It is a segmentation fault. Also does it come under run time memory error ?

严格来说,它是一种未定义的行为.您可能会或可能不会遇到分段错误.什么事情都可能发生.

Strictly speaking, its an undefined behavior. You may or may not get segmentation fault. Any thing could happen.

声明

char *str = "hellow Ghost";  

等价于

char const *str = "hellow Ghost";  

字符串文字存储在只读部分,任何修改它的尝试都会调用 UB.

String literals are stored in read-only section and any attempt to modify it invokes UB.

C11:J.2 未定义行为:

在以下情况下行为未定义:
...
― 程序尝试修改字符串文字 (6.4.5).

The behavior is undefined in the following circumstances:
...
― The program attempts to modify a string literal (6.4.5).

相关文章