MEX file crashing for an array of cell
조회 수: 2 (최근 30일)
이전 댓글 표시
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);
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
댓글 수: 0
채택된 답변
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!