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

1 view (last 30 days)
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?

Accepted Answer

James Tursa
James Tursa on 7 Mar 2013
Edited: James Tursa on 7 Mar 2013
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");
}

More Answers (0)

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!