MEX file crashing for an array of cell

조회 수: 2 (최근 30일)
Ubaid Ullah
Ubaid Ullah 2015년 7월 2일
댓글: Ubaid Ullah 2015년 7월 3일
Hello!
I have written a MEX file that takes in a cell array of double matrices, each of dimension 250x1000. The cell array dimensions are 29x1. The MEX file is assigning the value 3 to all the entries of the matrices. However, whenever I call the MEX file, MATLAB crashes. I have no idea why this is happening as the index of my matrices are in the allowed range.
To reproduce the bug/error, please run the following code on the attached files:
load test;
test(pp);
The files are large in size and are available here.
For a quick review, the test.c file is as follows:
#include <math.h>
#include <matrix.h>
#include <mex.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
const mwSize *dims;
const mxArray *cell;
const mxArray *cellArray;
double *inMatrix;
int mom, cellSize, jcell;
mwIndex i, j, count;
mwSize ncol, nrow;
// Read the cell
cell = prhs[0];
dims = mxGetDimensions(prhs[0]);
for (jcell=1; jcell<dims[0]; jcell++) {
cellArray = mxGetCell(cell,jcell);
inMatrix = mxGetPr(cellArray);
nrow = mxGetM(cellArray);
ncol = mxGetN(cellArray);
printf("%d, %d, %d\n", nrow, ncol, cellSize);
count = 0;
for(i=0;i<nrow;i++){
for(j=0;j<ncol;j++){
inMatrix[count] = 3;
count++;
}
}
}
}
Thanks

채택된 답변

Jan
Jan 2015년 7월 2일
If you want to assign all elements of the cell array, start at jcell=0 (as in the example http://www.mathworks.com/matlabcentral/answers/84135-getting-the-contents-from-cells-in-a-cell-array-using-mex).
mxGetCell replies a NULL pointer if the input is not a cell or if the cell element is not initialized. Check this in every case:
cellArray = mxGetCell(cell,jcell);
if (cellArray == NULL) {
... perform an error or an exception
}
You are writing directly into the input array. This is dangerous, because you do not check if this is a shared array. Never modify the inputs in a C-Mex function, if you are not really sure about what you are doing. But here this can lead to bad values in Matlab, but not to a crash.
jcell is an int and dims an mwSize. Are you sure that jcell<dims[0] does, what you expect? The same happens for i, j and nrow, ncol. Better rely on the same integer types.
  댓글 수: 1
Ubaid Ullah
Ubaid Ullah 2015년 7월 3일
Thanks .. actually some of the matrices in the array were of type SPARSE and some were of type FULL. The SPARSE matrices were creating problem as I was treating them full matrices, assuming they have nrowxncol size.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by