ofstream在极其简单的程序(GCC/Code::Blocks)中首次输出时崩溃

ofstream crashes on first output in extremely simple program (GCC/Code::Blocks)

本文关键字:Blocks 崩溃 输出 Code 简单 GCC 程序 ofstream      更新时间:2023-10-16

我有一个跨平台的日志记录应用程序,我周末在Windows上使用MSVC开发,然后在今天早上使用GCC/Code::Blocks在我的Linux盒子上,一旦它使用ofstream打开输出文件就会崩溃。

具体代码如下所示,实际上是程序中运行的前 8 行

stringstream strFile;
strFile<<filename;
strFile<<".result.out";
out.open(strFile.str().c_str());
out<<"Count"<<"t";
out<<"TM"<<"t";
out<<"Type"<<"t";
out<<"Seconds"<<"t";

在找出问题后,我后来制作了一个具有相同症状的最小应用程序

#pragma pack(1) // remove this and it will run without incident
#include <fstream>
using namespace std;
int main()
{
    ofstream out;
    out.open("test.txt");
    for(int x = 0;x < 10000; x++)
    {
      out<<"This is a test"<<endl; // crashes on first output
    }
    out.close();
    return 0;
}

#pragma pack(1)更改所有后续包含的头文件的 ABI,使标准C++库(.so.a(与您的应用程序不兼容。

解决方案是 删除该#pragma pack(1) .将填料单独应用于您的结构。

我强烈建议大家停止使用这些pragma pack属性(因为他们可以逃脱,我也在生产中看到这种情况(。

相反,根据需要使用编译器的语法(即 attribute packed (。