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!