I have a very simple program, listed below, which reads a value from a .mat
file (a data file from Matlab) and prints it. For some reason, I get a segfault error after exiting main() - I can run gdb my_program
and step through the entire method, but as soon as main()
finishes, I enter some method in a Matlab related library (libmwfl.so
, a dependency of libmat.so
) which throws a segfault.
I am completely new to C programming, but some reading up I suspect that I'm either somehow corrupting the stack or calling some destructor twice. However, I can't see any of those in my code - and as I said, I can step through my code with the debugger without problems.
What am I doing wrong here?
#include <stdlib.h>
#include <stdio.h>
#include <mat.h>
int main(int argc, char *argv[]) {
double value;
MATFile *datafile;
datafile = matOpen("test.mat", "r");
mxArray *mxv;
mxv = matGetVariable(datafile, "value");
value = *mxGetPr(mxv);
mxFree(mxv);
matClose(datafile);
printf("The value fetched from the .mat file was: %f", value);
return 0;
}
The documentation recommends to use the function mxDestroyArray
instead of mxFree
to free an mxArray
. By using mxFree
you probably mess up the matlab's heap. From the documentation
Improperly Destroying an mxArray
You cannot use
mxFree
to destroy anmxArray
.Warning: You are attempting to call
mxFree
on a<class-id>
array. The destructor formxArrays
ismxDestroyArray
; please call this instead. MATLAB will attempt to fix the problem and continue, but this will result in memory faults in future releases.Example That Causes Warning
In the following example,
mxFree
does not destroy the array object. This operation frees the structure header associated with the array, but MATLAB will still operate as if the array object needs to be destroyed. Thus MATLAB will try to destroy the array object, and in the process, attempt to free its structure header again.
mxArray *temp = mxCreateDoubleMatrix(1,1,mxREAL);
...
mxFree(temp); /* INCORRECT */
Solution.
Call
mxDestroyArray
instead.
mxDestroyArray(temp); /* CORRECT */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With