g++ 9.2.1 (Linux) 会导致 seg 错误,但 Windows 上的代码块不会

g++ 9.2.1 (Linux) causes seg fault but Codeblocks on windows does not

本文关键字:Windows 代码 错误 Linux g++ seg      更新时间:2023-10-16

以下简单代码(二进制文件处理(在与Windows的Codeblocks 17.12(mingw32-g++(捆绑在一起的编译器上运行良好,但在Linux的g++ 9.2.1(在Ubuntu 19.10上(中给出了分段错误:

#include <iostream>
#include <fstream>
using namespace std;
class A {
public:
int x;
string y;
};
int main()
{
ofstream k;
A m;
m.x = 10;
m.y = "Hello";
k.open("file.dat", ios::binary);
k.write(reinterpret_cast<char *>(&m), sizeof(A));
k.close();
ifstream i;
A t;
i.open("file.dat", ios::binary);
i.seekg(0, ios::beg);
i.read(reinterpret_cast<char *>(&t), sizeof(A));
cout << t.x << " " << t.y;
i.close();
return 0;
}

我做错了什么吗,Windows上的最小g ++可以原谅我,但g++ - Linux不是?还是我发现了错误?

程序具有未定义的行为。

你不能像这样std::string字节序列化复杂的对象。

未定义行为的结果可能会有所不同;在 Linux 安装中,您可能会目睹"小字符串优化",其中字符串数据足够小,可以放入一点就地缓冲区中。这样可以避免导致Windows崩溃的任何动态内存。也许 Windows 正在检测不良行为,或者它可能具有较小的 SSO 缓冲区,或者可能根本没有!

但是无论哪种方式,代码仍然具有未定义的行为。