Occasionally we need to compute the size of an object that does not yet
exist, or a subscript that may fall out of bounds. It’s easy to miss
the edge cases where results overflow, creating a nasty, subtle bug, even
in the presence of type safety. Ideally such computations happen in
specialized code, such as inside an allocator (calloc
, reallocarray
)
and not outside by the allocatee (i.e. malloc
). Mitigations exist with
different trade-offs: arbitrary precision, or using a wider fixed integer
— i.e. 128-bit integers on 64-bit hosts. In the typical case, working only
with fixed size-type integers, I’ve come up with a set of guidelines to
avoid overflows in the edge cases.