...
The function 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 table
. Because 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 table
.
Compliant Solution 1
In this compliant solution, the parameter pos
is declared as size_t
, which prevents passing of negative arguments (see INT01-CPP. Use rsize_t or size_t for all integer values representing the size of an object).
Code Block |
---|
|
enum { TABLESIZE = 100 };
int *table = NULL;
int insert_in_table(size_t pos, int value){
if (!table) {
table = (int *)malloc(sizeof(int) * TABLESIZE);
}
if (pos >= TABLESIZE) {
return -1;
}
table[pos] = value;
return 0;
}
|
Compliant Solution 2
Wiki Markup |
---|
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 {{array\[\]}} of {{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 {{n}}. |
Code Block |
---|
|
template <typename T> void clear(T array[], size_t n) {
for (size_t i = 0; i < n; ++i) {
array[i] = 0;
}
}
template <typename T, size_t n>
inline void clear(T (&array)[n]) {
clear(array, n);
}
int int_array[12];
clear(int_array); // deduce T is int, and that n is 12
|
Wiki Markup |
---|
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 {{T}} is {{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. |
Risk Assessment
Using an invalid array index can result in an arbitrary memory overwrite or abnormal program termination.
...