什么是分段错误? [英] What is a segmentation fault?

查看:35
本文介绍了什么是分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是分段错误?C 和 C++ 有什么不同?分段错误和悬空指针有什么关系?

What is a segmentation fault? Is it different in C and C++? How are segmentation faults and dangling pointers related?

推荐答案

分段错误是由于访问不属于你"的内存而导致的一种特定类型的错误.它是一种辅助机制,可防止您破坏内存并引入难以调试的内存错误.每当您遇到段错误时,您就知道自己在内存方面做错了——访问已被释放的变量、写入内存的只读部分等.在大多数让您陷入混乱的语言中,段错误本质上是相同的对于内存管理,C 和 C++ 中的段错误之间没有主要区别.

Segmentation fault is a specific kind of error caused by accessing memory that "does not belong to you." It’s a helper mechanism that keeps you from corrupting the memory and introducing hard-to-debug memory bugs. Whenever you get a segfault you know you are doing something wrong with memory – accessing a variable that has already been freed, writing to a read-only portion of the memory, etc. Segmentation fault is essentially the same in most languages that let you mess with memory management, there is no principal difference between segfaults in C and C++.

产生段错误的方法有很多种,至少在 C(++) 等低级语言中是这样.获取段错误的常见方法是取消引用空指针:

There are many ways to get a segfault, at least in the lower-level languages such as C(++). A common way to get a segfault is to dereference a null pointer:

int *p = NULL;
*p = 1;

当您尝试写入标记为只读的内存部分时,会发生另一个段错误:

Another segfault happens when you try to write to a portion of memory that was marked as read-only:

char *str = "Foo"; // Compiler marks the constant string as read-only
*str = 'b'; // Which means this is illegal and results in a segfault

悬空指针指向一个不再存在的东西,比如这里:

Dangling pointer points to a thing that does not exist anymore, like here:

char *p = NULL;
{
    char c;
    p = &c;
}
// Now p is dangling

指针p 悬垂,因为它指向字符变量c,该变量在块结束后不复存在.当您尝试取消引用悬空指针(如 *p='A')时,您可能会遇到段错误.

The pointer p dangles because it points to the character variable c that ceased to exist after the block ended. And when you try to dereference dangling pointer (like *p='A'), you would probably get a segfault.

这篇关于什么是分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆