getting seg fault while reading from a binary file that is created by the same code
I have written this code to make a binary file of float numbers, but I get a segmentation fault error at the end. It writes 9000 float numbers to the file but when reading it only reads 4096 of them. When I run the executable file a few times the number of bytes it reads switches between 4096, 8192 and 9000. but I have seg fault always there...
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();
There is an error in your code. There is no need to take address of pointers.
//out.write((char *) &realRef, length*sizeof(float));
out.write((char *) realRef, length*sizeof(float));
//in.read((char *) &readTest, size);
in.read((char *) readTest, size);
Your Code updated:
out.write((char *) realRef, length*sizeof(float)); //length is 9000in.read((char *) readTest, size);
You were passing address of pointer.
The segfault is because you read and write from the pointers themselves, not what is pointed to. Remove the &
from the write and read statements.
It is also generally a good idea to check the value returned by write, to see how much was actually written.
There is an error in your first line:
float *realRef = new float [length];
new returns a pointer to the newly allocated memory. The array brackets are also translated to a pointer. So in effect you do
float* realRef = float**(malloc(...))
The right way to do this would be
float* realRef = float[length]
精彩评论