フィルターのクリア

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");
}
  1 件のコメント
Jan
Jan 2013 年 4 月 29 日
I have accepted this answer.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWrite 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