Reputation: 3391
I'm running a 64-bit C++ program in VS2012 that processes images and writes the results to a MAT file. For whatever reason, after 508 working iterations, I get:
"Unhandled exception at ____ (libmat.dll) in Program.exe:____. Access violation writing location ____." (Underscores represent address locations)
However, if I restart the program on image number 509 (changing nothing else; just a restart), it works just fine for the next 508 images and then hands me the same error again.
A comment on an earlier, less-detailed post said it may be some memory issue. Perhaps I'm not handling garbage collection properly? I can't figure it out though.
For the record, all of the data being saved to files ends up in a 127x47 (row x col) double matrix. That means each of the 508 successful files contained 5969 doubles (plus whatever metadata goes into a MAT file). Perhaps some memory limit gets reached because I don't clear it properly?
The code in question is below:
void writeMat (void * data, int rows, int cols, std::string fname)
{
// Copies data to MATLAB format matrix
mxArray * mat;
mat = mxCreateDoubleMatrix(rows, cols, mxREAL);
memcpy((void*)mxGetPr(mat), data, rows * cols * sizeof(double));
// Creates output file
MATFile * output;
std::string matFilename = fname + ".mat"; // Output filename
std::string varName = "tmp"; // Storage variable in MAT file
output = matOpen(matFilename.c_str(), "w"); // Opens MAT file for writing
if (output == NULL) {
printf("Error creating file");
}
// Adds data variable to MAT file
int status = matPutVariable(output, varName.c_str(), mat);
if (status != 0)
{
printf("Error writing mat file");
}
mxDestroyArray(mat); // Free up memory
}
Any help would be appreciated. Thanks in advance!
Upvotes: 0
Views: 266
Reputation: 213170
It appears that you are running out of file handles, because you keep calling matOpen
but then don't subsequently call matClose
. Most systems impose an upper limit on the number of concurrently open files - it would appear that on your system this limit is 512 - there are already a few files open, so when you get to around the 508th iteration you run out of file handles.
Having said that, you should not see a crash - you have error checking on matOpen and this should fail gracefully when you try to open too many files, but evidently it doesn't!
Upvotes: 1