意外的运行时错误(分段错误)
Unexpected runtime error (segmentation fault)
我目前正在优化内存密集型应用程序以占用较少的内存。我在下面的代码中尝试做的是动态地分配ifstream
和ofstream
的文件流对象,以便在不再需要使用后准确地释放它们。该代码非常适合ofstream
的分配/取消分配,但由于取消分配ifstream
的内存内容时可能存在分段错误而在运行时崩溃。以下是原始代码的片段:
#include <fstream>
using namespace std;
// Dummy class to emulate the issue at hand
class dummy {
private:
int randINT;
static bool isSeeded;
public:
dummy() { randINT=rand(); }
int getVal() { return randINT; }
};
bool dummy::isSeeded=false;
int main(int argc, const char* argv[]) {
// Binary file I/O starts here
dummy * obj;
ofstream * outputFile;
ifstream * inputFile;
outputFile=new ofstream("bFile.bin",ios::binary);
if (!(*outputFile).fail()) {
obj=new dummy;
cout << "Value to be stored: " << (*obj).getVal() << "n";
(*outputFile).write((char *) obj, sizeof(*obj)); // Save object to file
(*outputFile).close();
delete obj;
// don't assign NULL to obj; obj MUST retain the address of the previous object it pointed to
} else {
cout << "Error in opening bFile.bin for writing data.n";
exit(1);
}
delete outputFile; // This line throws no errors!
inputFile=new ifstream("bFile.bin",ios::binary);
if (!(*inputFile).fail()) {
(*inputFile).read((char *) obj,sizeof(dummy)); // Read the object of type 'dummy' from the binary file and allocate the object at the address pointed by 'obj' i.e. the address of the previously de-allocated object of type 'dummy'
cout << "Stored Value: " << (*obj).getVal() << "n";
(*inputFile).close();
} else {
cout << "Error in opening bFile.bin for reading data.n";
exit(1);
}
delete inputFile; // Runtime error is thrown here for no reason!
cout << "n-----END OF PROGRAM-----n";
}
上面的代码在用户调用保存函数时将对象保存到二进制文件中。如上面的代码中所述,取消分配指针inputFile
会引发运行时错误。
请注意,我正在使用clang(更具体地说,clang++)来编译项目。
提前谢谢。
std::basic_istream::read(char_type*address, streamsize count)
最多读取count
个字符并将它们放在address
。它不会在address
创建任何对象,正如你似乎相信的那样。address
必须指向大小至少为count*sizeof(char_type)
的有效内存块。通过传递delete
d 对象的地址,您违反了该条件:您的代码已损坏,分段错误并非意外。
编辑
你正在做的是未定义的行为,做空 UB。当你这样做时,没有任何保证,任何关于以什么顺序发生的事情的逻辑都是无效的。该程序被允许做任何事情,包括立即崩溃,运行一段时间然后崩溃,或"让恶魔从你的鼻子里飞出来"。
在您的情况下,我怀疑std::basic_istream::read()
写入未受保护的内存会导致某些数据被覆盖,例如另一个对象的地址,这后来会导致分段错误。但这纯粹是猜测,并不值得追求。
在您的情况下,不会创建任何对象。二进制文件只包含一些字节。read()
将它们复制到提供的地址,该地址不是为此目的保留的。要避免 UB,只需添加
obj = new dummy;
在read
创建对象之前。
如果要重用上一个对象的内存,可以使用放置 new(请参阅该链接的第 9 点和第 10 点)。例如
char*buffer = nullptr; // pointer to potential memory buffer
if(writing) {
if(!buffer)
buffer = new char[sizeof(dummy)]; // reserve memory buffer
auto pobj = new(buffer) dummy(args); // create object in buffer
write(buffer,sizeof(dummy)); // write bytes of object
pobj->~pobj(); // destruct object, but don't free buffer
}
if(reading) {
if(!buffer)
buffer = new char[sizeof(dummy)]; // not required if writing earlier
read(buffer,sizeof(dummy)); // read bytes into object
auto pobj = reinterpret_case<dummy*>(buffer); // no guarantees here
use(pobj); // do something with the object read
pobj->~pobj(); // destruct object
}
delete[] buffer; // free reserved memory
请注意,如果读取未生成有效对象,则该对象的后续使用(即对其析构函数的调用)可能会崩溃。
然而,所有这些微优化无论如何都是毫无意义的(只有当你能避免多次调用new
和delete
时,才值得这样做)。不要浪费你的时间。
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)