This guideline has been labeled void and designated for future elimination from the C++ Secure Coding Practices. It has not been erased yet in case it contains information that might still be useful.
Ensuring that arrays are used securely is almost entirely the responsibility of the programmer. One of the principle problems with arrays is determining their size.
Non-Compliant Code Example
This non-compliant code example shows a function
insert_in_table() that takes two
value, both of which can be influenced by data originating from untrusted sources. The function uses a global variable
table to determine if storage has been allocated for an array of 100 integer elements and allocates the memory if it has not already been allocated. The function then performs a range check to ensure that
pos does not exceed the upper bound of the array but fails to check the lower bound for
pos has been declared as a (signed)
int, this parameter can easily assume a negative value, resulting in a write outside the bounds of the memory referenced by
Compliant Solution 1
In this compliant solution, the parameter
pos is now an unsigned integer type, preventing passing of negative arguments.
Compliant Solution 2
Specialized function templates can be used to define functions that accept an array of a generic type
T of size
n. The compiler can perform template argument deduction for function templates to properly deduce both the type and size. This compliant solution defines a function template for a function
clear() that takes a template parameter
T elements and an actual length parameter of type
size_t. This is not particularly useful yet, as we have already seen that passing an array with an explicit size parameter is a common (but error prone) idiom. However, you can also define a specialization of the function template that includes a template parameter
n of type
size_t in addition to the original type parameter. The inline function
clear() has one parameter: an array of type
T elements of fixed length
The function template and specialized function template can be used in a straightforward manner. This example declares an array of 12 integers named
int_array and invokes the
clear() function passing
int_array as an argument. The compiler matches this invocation to
inline void clear(T (&array)[n]) because this definition most closely matches the actual argument type of array of
int. The compiler deduces that the type
int and that
n is 12, separating the size
n from the pointer to the array of
int before invoking the function template for
clear(). This use of specialized function templates guarantees that the
clear() function has the correct array size.
Out-of-range indices can allow an attacker to execute arbitrary code with the privileges of the vulnerable process.