什么可能导致C ++中的分段错误? [英] What can cause segmentation faults in C++?

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

问题描述

我注意到C ++中的分段错误的常见原因列表没有问题,所以我想我会添加它。

I noticed there's not question with a list of common causes of segmentation faults in C++, so I thought I'd add it.

自然是社区Wiki,因为没有正确答案。

Naturally it's community Wiki, since there's no one correct answer.

我认为这对于学习C ++的新程序员可能是有用的,如果你不同意,可以随意关闭它。 / p>

I think this might be useful for newer programmers learning C++, feel free to close it if you disagree.

推荐答案

分段故障是由对内存的不良访问引起的,只有当您的操作系统有MMU时。

Segmentation fault is caused by bad accesses to memory, only if your OS has a MMU. Otherwise, you won't get it but only strange behavior.

虚拟内存(可访问的整个内存= 2 ^ sizeof(指针)类型))以名称为页面或段的单位映射到物理内存(分页替代分段,但它们仍在使用)。

The virtual memory (the entire memory accessible to you = 2 ^ sizeof(pointer type)) is mapped to physical memory in units named pages or segments (paging superseded segmentation but they are still used).

每个页面都有一些保护权限,如果您尝试从具有无读访问权限的页面读取,您会得到一个segfault。如果你试图写一个只读的位置,你会得到一个SIGSEGV。

Each page has some protection rights, if you try to read from a page with no-read access you'll get a segfault. If you try to write to a readonly location you'll get a SIGSEGV.

如果你有一个unitialized指针,并使用它可能会发生,它会指向另一个好位置,所以你不会得到一个segfault。如果你有一个小的数组读取它的绑定可能会损坏其他内存区域,如果它没有超过页面边界。

If you have an unitialized pointer and use it it may happen that it will point to another good location so you'll don't get a segfault. If you have a small array reading after it's bound may corrupt other memory areas if it doesn't get past the page boundary.

此外,由于有很多页,所有这些都是真正映射的。如果您触摸未映射的页面,您会得到一个segfault。实际上,对非映射页面的任何访问都必须考虑写入时的副本,交换页面,延迟加载,内存映射文件和其他事情。请参见本文页面错误处理,特别是其中的第二个图表,发布于此处

Also, since there are many pages, not all of them are really mapped. If you touch a non-mapped page you'll get a segfault. Actually, any access to a non mapped page will have to take into account copy on write, pages on swap, lazy loading, memory mapped files and other things. See this article on page fault handling, especially the second diagram there, posted here below too (but read the article for more explanations)

您主要感兴趣的是在用户空间和导致SIGSEGV的所有路径发生了什么。但是内核空间也很有趣。

You are mainly interested in what happens in user space and all paths leading to SIGSEGV. but kernel space is also interesting.

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

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