I'm reading data from mat-files with code below. The code starts to search all subdirectories for mat-files like Dog_1/Dog_1_interictal_segment_1/0001.mat and transposing the matrix data into a csv file.
The problem occurs at line 139 when memory is beeing freed twice using Mat_VarFree(). The program aborts with
*** Error in `./a.out': double free or corruption (fasttop): 0x0000000000b66470 ***
as mentioned, when Mat_VarFree is called twice. If I remove one of the Mat_VarFree's a memory leak is born.
What can I do??
Thanks
#include <regex>
#include <iostream>
#include <boost/filesystem.hpp>
#include <matio.h>
#include <string>
#include <fstream>
using namespace std;
using namespace boost::filesystem;
// global def
smatch m;
regex r (
"^"
"(Dog|Person)_"
"([0-9])_"
"(interictal|preictal|test)_"
"(segment)_"
"(0{0,3}([1-9][0-9]{0,3}))"
"(\\.mat)"
"$"
);
path p("csv");
int main(int argc, char *argv[])
{
// mr proper
if (is_directory(p))
{
for (directory_iterator i(p), j; i!=j; ++i)
{
remove_all(i->path());
}
}
else
{
create_directory(p);
}
// work
for (recursive_directory_iterator i("."),j; i!=j; ++i)
{
if (!is_directory(i->path()))
{
if (regex_match(i->path().filename().string(), m, r))
{
// for later use
string m0 = m[0];
string m1 = m[1];
string m2 = m[2];
string m3 = m[3];
string m4 = m[4];
string m5 = m[5];
string m6 = m[6];
// mat file
auto mfilename = i->path().string();
auto mfile = Mat_Open(mfilename.c_str(), MAT_ACC_RDONLY);
if (NULL == mfile)
{
cerr
<< "Error opening MAT file '"
<< i->path().filename().string()
<< "'"
<< endl;
return EXIT_FAILURE;
}
// mat var
auto mvarname = m3 + "_" + m4 + "_" + m6;
auto mvar = Mat_VarReadInfo(mfile, mvarname.c_str());
if (NULL == mvar)
{
cerr
<< "Error reading MAT var '"
<< mvarname
<< "' in file '"
<< mfilename
<< "'"
<< endl;
Mat_Close(mfile);
mfile = NULL;
return EXIT_FAILURE;
}
// mat struct
auto mstructname = "data";
auto mstruct = Mat_VarGetStructFieldByName(mvar,mstructname,0);
if ( NULL == mstruct )
{
cerr
<< "Error reading MAT struct in var '"
<< mvarname
<< "' in file '"
<< mfilename
<< "'"
<< endl;
Mat_VarFree(mvar);
mvar = NULL;
Mat_Close(mfile);
mfile = NULL;
return EXIT_FAILURE;
}
// mstruct to array
int rows = mstruct->dims[0];
int cols = mstruct->dims[1];
int start[2] = {0,0};
int stride[2] = {1,1};
int edge[2] = {rows, cols};
double * data = (double *)malloc(sizeof(double)*rows*cols);
Mat_VarReadData(mfile, mstruct, data, start, stride, edge);
// csv file
auto cfilename = p.string() + "/" + m3 + "_" + m4 + "_" + m5;
std::ofstream cfile(cfilename, std::ofstream::out);
cout << cfilename << endl;
for (int i=0; i!=cols; ++i) {
for (int j=0; j<rows; ++j) {
cfile << data[j+(rows*i)] << "\t";
}
cfile << "\n";
}
cfile.close();
// mr proper
Mat_VarFree(mstruct);
mstruct = NULL;
Mat_VarFree(mvar);
mvar = NULL;
Mat_Close(mfile);
mfile = NULL;
}
}
}
return EXIT_SUCCESS;
}