读取由相同代码创建的二进制文件时出现segfault

getting seg fault while reading from a binary file that is created by the same code

本文关键字:二进制文件 segfault 创建 代码 读取      更新时间:2023-10-16

我已经编写了这段代码,使浮点数的二进制文件,但我得到一个分割错误在结束。它将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]