The vulnerability as described in ISO/IEC 24772-1:2022 exists in C++, but can be mitigated using features provided by the language.
A buffer overflow occurs when some number of elements is copied from one buffer to another and the amount being copied is greater than is allocated for the destination buffer. This is a special case of 6.8 Buffer Boundary Violation [HCB]. The C library functions or hand-written loops for copying bytes or C-style strings are especially prone to this vulnerability.
As with clause 6.8 [HCB], in most cases the vulnerability can be avoided by using library classes, such as std::vector
or std::string
, which provide a copy operations operator that adjust the size of the target to fit the object being copied.
The standard library algorithms that copy into a target range can suffer from this vulnerability. In the case of potential overflow, the programmer must either ensure automatic extension of the underlying container, such as by using std::back_inserter(container)
as the output iterator, or ensure that the output range has sufficient space available. In the case of overlapping input and output ranges, the suitable copying algorithm must be selected, depending on the relative ordering of the ranges. In general, this situation can be avoided by using a more appropriate algorithm, for example, std::rotate
.
For arrays with fixed sizes the assignment operator or copy-constructor of std::array
is the means of safe array copying.
If a system requires its own container types with dynamic size, a naïve implementation might attempt to keep the copying external, like with C-style arrays. Such external copying should be avoided.
To avoid the vulnerability or mitigate its ill effects, C++ software developers can:
Use the avoidance mechanisms of ISO/IEC 24772-1:2022 clause 6.10.5.
Use standard library containers instead of C-style arrays, such as std::vector
or std::array
, that provide copying mechanisms that ensure the target array is large enough for the indicated source.
When using standard library algorithms that copy into an output range, ensure that either the output range is extended automatically or has sufficient space available.
Sidestep the need to use a copy algorithm on overlapping ranges, by selecting a more appropriate algorithm, such as std::rotate
.
If a system requires its own container types with dynamic size, ensure that their copy operations are correct and do not require loops or algorithms for copying their content.
If copying C-style arrays is unavoidable, statically show that an access outside of the array cannot occur, or alternatively perform range checking before copying the array.
Avoid using the copying functions from the headers