Length-prefix validation before allocation (source code)

= Length-prefix validation before allocation

\b[Length-prefix validation before allocation] checks that an encoded payload length is permitted and safely usable before requesting <memory allocation> based on it. A <fixed-width length field> bounds what the encoding can represent; an application can impose a smaller limit. TLS vectors, for example, have explicitly specified minimum and maximum byte lengths.<The Transport Layer Security Protocol Version 1.3 (RFC 8446)>[§3.4, variable-length vectors and permitted bounds]{ref}

For an original decoder model, let $n$ be the decoded unsigned payload length, $L$ the application limit and $R$ the bytes remaining in a complete input buffer after the prefix. Before allocating or consuming that payload, require
$$
0\le n\le L,\qquad n\le R.
$$
Check that the complete prefix is available before reading it. For a two-byte big-endian prefix `02 01`, $n=513$. With $L=400$ and $R=300$, the input fails both checks. Prefix `01 2c` instead declares $300$ bytes and satisfies these two bounds. The example counts only payload bytes in $n$.

Arithmetic needs its own bound. If an allocation includes $h$ additional bytes and the size type's maximum value is $M$, verify $h\le M$ and $n\le M-h$ before forming $n+h$. Computing the sum first can already cause <integer overflow>. Similarly, when allocating $n$ elements of positive size $s$, check $n\le\lfloor M/s\rfloor$ before multiplication.

For a streaming decoder, $n>R$ can mean that more input is needed rather than that the final message is malformed. It still does not justify consuming unavailable bytes or allocating beyond the stated resource limit. Nested fields need bounds relative to their enclosing field. These checks establish safe structural handling of a <length-prefixed encoding>; they do not authenticate the sender or validate the payload's meaning.