What can cause segmentation faults in C++?(什么会导致 C++ 中的分段错误?)
问题描述
我注意到 C++ 中的分段错误的常见原因列表没有问题,所以我想我会添加它.
自然是社区 Wiki,因为没有一个正确答案.
我认为这可能对学习 C++ 的新程序员有用,如果您不同意,请随时关闭它.
只有当你的操作系统有 MMU(
(来源:vistech.net 冠军)
您主要对用户空间中发生的事情以及通向 SIGSEGV 的所有路径感兴趣.但内核空间也很有趣.
I noticed there's not question with a list of common causes of segmentation faults in C++, so I thought I'd add it.
Naturally it's community Wiki, since there's no one correct answer.
I think this might be useful for newer programmers learning C++, feel free to close it if you disagree.
Segmentation fault is caused by bad accesses to memory, only if your OS has a MMU (Memory Management Unit). Otherwise, you won't get it but only strange behavior.
The virtual memory (the entire memory accessible to you = 2^(sizeof(pointer_type)*8)
(ie: 2^num_bits_in_pointer_type
)) is mapped to physical memory in units named pages or segments (paging superseded segmentation but they are still used).
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.
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.
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)
(source: champ at vistech.net)
You are mainly interested in what happens in user space and all paths leading to SIGSEGV. but kernel space is also interesting.
这篇关于什么会导致 C++ 中的分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:什么会导致 C++ 中的分段错误?
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01