读取由相同代码创建的二进制文件时出现segfault
getting seg fault while reading from a binary file that is created by the same code
我已经编写了这段代码,使浮点数的二进制文件,但我得到一个分割错误在结束。它将9000个浮点数写入文件,但在读取时只读取其中的4096个。当我运行可执行文件几次时,它读取的字节数在4096、8192和9000之间切换。但我总是有segfault…
float *realRef = new float [length]; //then filling it out...
ofstream out("blah.bin", ios::out | ios::binary);
out.write((char *) &realRef, length*sizeof(float)); //length is 9000
out.close();
ifstream in("blah.bin", ios::in | ios::binary);
float *readTest= new float[length];
in.seekg(0, ios::end);
size_t size=in.tellg(); // printing size shows 4096 BUT it should be 9000
in.seekg(0, ios::beg);
in.read((char *) &readTest, size);
cout << in.gcount() << " bytes read." << endl;
in.close();
您的代码中有错误。不需要取指针的地址
//out.write((char *) &realRef, length*sizeof(float));
out.write((char *) realRef, length*sizeof(float));
//in.read((char *) &readTest, size);
in.read((char *) readTest, size);
您的代码已更新:
<>之前出去了。write((char *) realRef, length*sizeof(float));//长度为9000
在。read((char *) readTest, size);
之前你正在传递指针的地址
段错误是因为读取和写入的是指针本身,而不是指针所指向的对象。从写和读语句中删除&
检查write返回的值,看看实际写了多少,通常也是一个好主意。
第一行错误:
float *realRef = new float [length];
new返回一个指向新分配内存的指针。数组括号也被转换为指针。所以实际上你可以输入
float* realRef = float**(malloc(...))
正确的方法是
float* realRef = float[length]
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 编译多个C++文件.调用二进制文件以运行代码
- 如何使用位字段将数据从二进制文件复制到结构中?
- uint8_t同一二进制文件的不同十进制值
- C++单个生成文件多个二进制文件
- 尝试将数字写入二进制文件时引发异常
- C++中读/写二进制文件
- 如何忽略某些二进制文件的执行?
- 对在不同二进制文件中创建的对象文件的依赖关系
- 读取由相同代码创建的二进制文件时出现segfault