Apparently I'm corrupting the stack, but how?

I have a very simple program, listed below, that reads a value from a .mat file (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 go through the whole method, but as soon as main() finishes, I enter some method into the Matlab-related library ( libmwfl.so , depending on libmat.so ) that generates segfault.

I am completely new to C programming, but some people read it, I suspect that I either somehow corrupt the stack or call the destructor twice . However, I do not see any of them in my code - and, as I said, I can easily execute my code with a debugger.

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; } 
+7
source share
1 answer

The documentation recommends using the mxDestroyArray function instead of mxFree to free up mxArray . Using mxFree , you are likely to mess up a bunch of matlab. From document

Incorrect destruction of mxArray

You cannot use mxFree to destroy mxArray .

Warning You are trying to call mxFree in an array of <class-id> . Destructor for mxArrays - mxDestroyArray ; please call it instead. MATLAB will try to solve the problem and continue, but this will lead to memory errors in future releases.

Warning Example

In the following example, mxFree does not destroy the array object. This operation releases the structure header associated with the array, but MATLAB will work as if the array object should be destroyed. Thus, MATLAB will try to destroy the array object and in this process will again try to free the structure header.

mxArray *temp = mxCreateDoubleMatrix(1,1,mxREAL);

  ... 

mxFree(temp); /* INCORRECT */

Decision.

Call mxDestroyArray .

mxDestroyArray(temp); /* CORRECT */

+9
source

All Articles