Code in Sprites.cpp depends on integer overflow
Pharap opened this issue · 1 comments
A while back when trying to port Arduboy2 to the Pokitto (a 32-bit environment) I discovered a section of code in Sprites.cpp
that depends on integer overflow.
The full tirade can be read here.
The short version is that I noticed ofs + WIDTH
was managing to get into the high 65000s,
which I correctly realised meant the code must be assuming that the value would wrap around.
It's quite a subtle bug because few people realise that (and I quote cppreference):
arithmetic operators do not accept types smaller than int as arguments
Hence the addition forces 32-bit arithmetic on a system where int
is 32 bits.
This is as per the rule:
unsigned char
,char8_t
(since C++20) orunsigned short
can be converted toint
if it can hold its entire value range, andunsigned int
otherwise;
The easiest solution is to replace all instances of ofs + WIDTH
with static_cast<uint16_t>(ofs + WIDTH)
or ((ofs + WIDTH) & 0xFFFFu)
.