【发布时间】:2022-06-14 01:07:25
【问题描述】:
我知道 Segmentation Fault 是一个一般性错误,可能是由不同的错误内存访问场景引起的。我试过了,但无法弄清楚我的代码有什么问题。
这是最小的可重现示例:
#include <filesystem>
#include <iostream>
using namespace std;
int main()
{
filesystem::path filePath("file");
if (filesystem::exists(filePath))
cout << "file exists" << endl;
else
cout << "file not found" << endl;
return 0;
}
这是构建命令和执行结果(目标文件不存在)。
$ g++ -std=c++17 main.cpp
$ ls
a.out main.cpp
$ ./a.out
file not found
Segmentation fault (core dumped)
$ g++ --version
g++ (Ubuntu 8.4.0-3ubuntu2) 8.4.0
...
调试显示分段错误发生在 filePath 破坏点,在标头的这一部分 (/usr/include/c++/8/bits/stl_vector.h):
/**
* The dtor only erases the elements, and note that if the
* elements themselves are pointers, the pointed-to memory is
* not touched in any way. Managing the pointer is the user's
* responsibility.
*/
~vector() _GLIBCXX_NOEXCEPT
{
std::_Destroy(this->_M_impl._M_start, this->_M_impl._M_finish,
_M_get_Tp_allocator());
_GLIBCXX_ASAN_ANNOTATE_BEFORE_DEALLOC;
}
代码或构建命令有什么问题?
【问题讨论】:
-
主流编译器附带的标准库实现中出现错误的几率非常低。它会发生,但请确保您没有以错误的值调用库,并且您之前没有损坏内存。
-
Task-- 什么是Task?请发布minimal reproducible example。据我们所知,问题在于Task没有正确的复制语义,因为您在不同的地方复制它。 -
您能否显示一个显示此分段错误的minimal reproducible example?否则,我们必须猜测还有哪些代码允许该函数运行,以及其他代码是否存在错误。
-
bool List::readFromFile()-- 加上这一切,代码是一个成员函数。如果readFromFile不是静态函数,则List必须是任何 代码的有效对象才能具有正确的行为。我们不知道List对象是在何处、何时或如何创建、使用等的。 -
你的代码有一个问题是
while (!ifs.eof()) { getline(ifs, strTemp);应该写成while (getline(ifs, strTemp)) {,但这不是你崩溃的原因。