什么是分割的错吗? [英] What is a segmentation fault?

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

问题描述

什么是分割的错吗?它是在C和C ++有什么不同?是如何分割的相关故障和悬摆指针?

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

推荐答案

分段故障是一种特定类型的错误引起的内存访问说:不属于你的。这是让你去破坏内存的辅助机制,引入难以调试内存错误。每当你得到一个段错误,你知道你在做什么毛病记忆 - 访问已被释放的变量,写入内存等分割故障只读部分基本上是可以让你惹大多数语言相同内存管理,没有在C和C ++设计缺陷之间没有principial区别。

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 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 the memory management, there is no principial 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 any more, 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 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天全站免登陆