I spent part of yesterday and today tracking down a bug in some Matlab code. I had thought my problem was indexing (with many structures that I didn't define and am still getting used to), but it turned out to be an overflow bug. I missed this for a very specific reason:
>> uint8(2) - uint8(1)
ans =
1
>> uint8(2) - uint8(2)
ans =
0
>> uint8(2) - uint8(3)
ans =
0
I would have expected the last one to be something like -1
(or 255
). In the middle of a big vector, the erroneous 0
s were difficult to detect, but a 255
would have stood out easily.
Any tips on how to detect these problems easily in the future? (Ideally, I'd like to turn off the overflow checking to make it work like C.) Changing to double
works, of course, but if I don't realize it's a uint8
to begin with, that doesn't help.
To disable integer overflow support: In a code generation configuration object for MEX or standalone code (static library, dynamically linked library, or executable program), set the SaturateOnIntegerOverflow property to false . In the MATLAB Coder™ app, set Saturate on integer overflow to No .
Most computers have two dedicated processor flags to check for overflow conditions. The carry flag is set when the result of an addition or subtraction, considering the operands and result as unsigned numbers, does not fit in the given number of bits.
look into bignum arithmetic libraries. they'll be a bit slower than standard C arithmetic but at least you won't get overflow. also many standard math functions (exp etc) will set errno to ERANGE in case of overflow. Usually, it is prevented by thinking carefully when writing code.
You can start by turning on integer warnings:
intwarning('on')
This will give you a warning when integer arithmetic overflows.
Beware though, as outlined here, this does slow down integer arithmetic so only use this during debug.
Starting with release R2010b and later, the function INTWARNING has been removed, along with these warning messages for integer math and conversion:
MATLAB:intConvertNaN
MATLAB:intConvertNonIntVal
MATLAB:intConvertOverflow
MATLAB:intMathOverflow
So using INTWARNING is no longer a viable option for determining when integer overflows occur. An alternative is to use the CLASS function to test the class of your data and recast it accordingly before performing the operation. Here's an example:
if strcmp(class(data),'uint8') %# Check if data is a uint8
data = double(data); %# Convert data to a double
end
You could also use the ISA function as well:
if ~isa(data,'single') %# Check if data is not a single
data = single(data); %# Convert data to a single
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With