g++ 9.2.1 (Linux) 会导致 seg 错误,但 Windows 上的代码块不会
g++ 9.2.1 (Linux) causes seg fault but Codeblocks on windows does not
以下简单代码(二进制文件处理(在与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 缓冲区,或者可能根本没有!
但是无论哪种方式,代码仍然具有未定义的行为。
相关文章:
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 在Linux for Windows上编译C++代码时出错
- 在 Linux 群集上运行 Windows C++代码
- 如何分析在 Windows 上运行C++代码?
- g++ 9.2.1 (Linux) 会导致 seg 错误,但 Windows 上的代码块不会
- 如何在 vim (windows) 中编译和运行 c++ 代码
- Windows Toast 通知不适用于 MS CPP 示例代码
- 如何在Visual Studio 2017中编译Windows XP的代码
- 如何在 Windows API 中检测带有虚拟代码的非字母?
- C++代码在 Linux 上按预期工作,但在 Windows 上则不然
- 我想使用 CMakeList 将 ODBC 集成到我的 Linux 和 Windows 代码中.txt但它只能在 Win
- 在Windows C 代码:: Blocks上的Boost Regex
- 如何从 Windows 代码页码获取 ICU 转换器
- 具有专有测试自动化功能的Windows代码覆盖率
- Windows代码块中OpenCV的未定义引用错误
- 为linux修改c++ Windows代码
- 我怎么能迁移视频为Windows代码更好的东西
- 在Windows/代码块上构建GLFW
- Windows C++代码(类似于CRON),每xx小时执行一次命令
- Windows C代码上的内存分配