필터 지우기
필터 지우기

In a Mex file, a for loop goes beyond the relational expression?

조회 수: 1 (최근 30일)
Jason
Jason 2013년 3월 7일
I keep getting a crash in a mex file. I have no clue why there is a problem other than using mwSize instead of something else.
here is code cut down to only the problem
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mwSize t, T;
T = mxGetN(prhs[0]);
for( t = T - 2; t >= 0; t--){
mexPrintf("Smooth %d\n",t);
mexEvalString("drawnow;");
}/*end of t=T-2:0;*/
return;
}
this gets compiled with the -largeArrayDims flag.
then in matlab:
a= zeros(50,200); and run the above on a
I expect the printed t to go from 198 to 0 and then stop. Instead, it runs into negative numbers and doesn't stop unless killed.
Anyone know why?

채택된 답변

James Tursa
James Tursa 2013년 3월 7일
편집: James Tursa 2013년 3월 7일
Depending on MATLAB version and platform and compile flags, mwSize can either be an int (a signed integer) or a size_t (an unsigned integer ... key point here). For your case you have mwSize as size_t, an unsigned integer. So t and T are unsigned. Thus the result of the test t>=0 will ALWAYS be true. Once you get past the t=0 case, the expression t-- actually does a wrap-around in modulo arithmetic to get a very large unsigned value (the max possible then it keeps going). Then you print out the results but use the wrong format code for this, %d which is for signed values. So the mexPrintf essentially interpretes this very large unsigned bit pattern (the most significant bit is set) as a signed integer and prints it out.
To demonstrate that mwSize is in fact unsigned you can try this:
if( (t = -1) > 0 ) {
mexPrintf("mwSize is unsigned\n");
}

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by