I would like to write a 2D integer array to a binary file in binarySave.cc and then read it in binaryRead.cc. But the execution of binaryRead gives: Segmentation fault (core dumped). However, when the contents of binarySave.cc and binaryRead.cc are placed to the same file (binarySaveRead.cc) the reading works like expected.
binarySave.cc
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int** a = new int*[10];
for(int i=0; i<10; ++i)
{
a[i] = new int[2];
}
for(int i=0; i<10; ++i)
{
a[i][0] = 1;
a[i][1] = 2;
}
ofstream out("test.bin", ios::binary);
if (out.is_open())
{
out.write((char*)a, 10*2*sizeof(int));
}
out.close();
for(int i=0; i<10; ++i)
{
delete [] a[i];
}
delete [] a;
return 0;
}
binaryRead.cc
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int** a = new int*[10];
for(int i=0; i<10; ++i)
{
a[i] = new int[2];
}
ifstream input("test.bin", ios::binary);
input.read((char*)a, 10*2*sizeof(int));
input.close();
for(int i=0; i<10; ++i)
{
std::cout<<a[i][0]<<" "<<a[i][1]<<std::endl; //segfault
}
for(int i=0; i<10; ++i)
{
delete [] a[i];
}
delete [] a;
return 0;
}
Execution gives
> ./binarySave
> ./binaryRead
Segmentation fault (core dumped)
But putting putting the exact same code to that same file makes it work.
binarySaveRead.cc
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int** a1 = new int*[10];
for(int i=0; i<10; ++i)
{
a1[i] = new int[2];
}
for(int i=0; i<10; ++i)
{
a1[i][0] = 1;
a1[i][1] = 2;
}
ofstream out("test2.bin", ios::binary);
if (out.is_open())
{
out.write((char*)a1, 10*2*sizeof(int));
}
out.close();
delete [] a1;
//-------------------
int** a2 = new int*[10];
for(int i=0; i<10; ++i)
{
a2[i] = new int[2];
}
ifstream input("test2.bin", ios::binary);
input.read((char*)a2, 10*2*sizeof(int));
input.close();
for(int i=0; i<10; ++i)
{
std::cout<<a2[i][0]<<" "<<a2[i][1]<<std::endl;
}
for(int i=0; i<10; ++i)
{
delete [] a2[i];
}
delete [] a2;
return 0;
}
The output:
> ./binarySaveRead
1 2
1 2
1 2
1 2
1 2
1 2
1 2
1 2
1 2
1 2
What is the problem when the write and read are in two files?
I am on openSuse 42.3 using g++ 4.8.5.