Info

This question is closed. Reopen it to edit or answer.

Segmentation Violation in a MEX file with Structure array as output.

1 view (last 30 days)
Hello all!
Well, I've been trying to run a MEX file where I really need the output to be a struct array, but it seems there are some issues considering memory allocation. So, let me present a simplified part of the code that probably causes the problem:
mxArray * mxp1, *mxp2, *mxp3;
int ** pr;
plhs[0] = mxCreateStructArray (ndim, dims, nfields, fieldnames);
mxp1 = mxCreateNumericArray (ndim, dims1 , mxINT32_CLASS, mxREAL);
mxp2 = mxCreateNumericArray (ndim, dims2 , mxINT32_CLASS, mxREAL);
mxp3 = mxCreateNumericArray (ndim, dims3 , mxINT32_CLASS, mxREAL);
mxSetField (plhs[0], index, fieldnames[0], mxp1);
mxSetField (plhs[0], index, fieldnames[1], mxp2);
mxSetField (plhs[0], index, fieldnames[2], mxp3);
pr = (int**) mxMalloc( 3 * sizeof(int*) );
pr [0] = (int*) mxGetData(mxp1);
pr [1] = (int*) mxGetData(mxp2);
pr [2] = (int*) mxGetData(mxp3);
As you can see, pr is an array of pointers. Later, each of its elements ( pr[0], pr[1], pr[2] ) will be the input arguments of a function that looks like:
int function (int* x1, int* x2, int* x3)
Most of the times when I run the above mex-file, I get a MATLAB system error indicating Segmentation Violation.
These are the last three steps from the Slack Trace report that seem to cause the problem:
[56] 0x7520ee1c C:\Windows\system32\kernel32.dll+00323100 (BaseThreadInitThunk+000018 )
[57] 0x777b37eb C:\Windows\SYSTEM32\ntdll.dll+00407531 (RtlInitializeExceptionChain+000239 )
[58] 0x777b37be C:\Windows\SYSTEM32\ntdll.dll+00407486 (RtlInitializeExceptionChain+000194 )
Let me note that there are also a few times that my mex-file returns a struct array, but with NULL fields.
I would be grateful if someone had some hint on this.
  1 Comment
Jan
Jan on 10 Aug 2014
In C all details matter. There could be a bug in the values of ndim, dims, nfields and index. The program might fail because you use an int pointer for a mxINT32_CLASS array, which leads to errors on 64 bit systems. So, without seeing the complete relevant code it is impossible to guess the problem(s).

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!