意外的运行时错误(分段错误)

Unexpected runtime error (segmentation fault)

本文关键字:错误 分段 运行时错误 意外      更新时间:2023-10-16

我目前正在优化内存密集型应用程序以占用较少的内存。我在下面的代码中尝试做的是动态地分配ifstreamofstream的文件流对象,以便在不再需要使用后准确地释放它们。该代码非常适合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)的有效内存块。通过传递deleted 对象的地址,您违反了该条件:您的代码已损坏,分段错误并非意外

编辑

你正在做的是未定义的行为,做空 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

请注意,如果读取未生成有效对象,则该对象的后续使用(即对其析构函数的调用)可能会崩溃。

然而,所有这些微优化无论如何都是毫无意义的(只有当你能避免多次调用newdelete时,才值得这样做)。不要浪费你的时间。