Here is a solution for this precise formula, the reasoning behind it won't work for the general case, but for the given one, and many others, it does.
Overflow happens precisely when size*3 + 1
is not representable, unsigned integer divisions can never overflow. So, your condition should be size*3 + 1 > max_value
. Here, max_value is the unsigned value with all bits set, which you generated with (size_t)-1
.
The +1
can simply moved to the right side without invoking overflow since max_value is definitely greater than 1, so we arrive at size*3 > max_value - 1
. Likewise, *3
can be moved without invoking overflow. So what you need to check is size > (max_value - 1)/3
.
Please note that, contrary to what I said originally (mea culpa), size > max_value/3
does not work because max_value is a multiple of 3 when the integer type is unsigned (the condition is that there is an even number of bits available for positive numbers). So, the when size is 0x5555
, we get 3*size = 0xffff
and 3*size + 1 = 0x0000
. Sorry for mixing that up.