...
However, the value of size
may be zero or excessive, potentially giving rise to a security vulnerability.
Compliant
...
Solution
This compliant solution ensures the size
argument used to allocate vla
is in a valid range (between 1 and a programmer-defined maximum); otherwise, it uses an algorithm that relies on dynamic memory allocation. The solution also avoids unsigned integer wrapping that, given a sufficiently large value of size
, would cause malloc
to allocate insufficient storage for the array.
...
The following noncompliant code example defines A
to be a variable length array type and then uses the sizeof
operator to compute its size at runtime. When the function is called with an argument greater than SIZE_MAX / (N * sizeof (int)
), the runtime sizeof
expression may wrap around, yielding a result that is smaller than the mathematical product N * n * sizeof (int)
. The call to malloc()
, when successful, will then allocate storage for fewer than n
elements of the array, causing one of the final memset
calls ()
calls in the for
loop to write past the end of that storage.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h> #include <string.h> enum { N = 4096 }; void* func(size_t n) { typedef int A [n][N]; A *array = malloc(sizeof (A)); for (size_t i = 0; i != n; ++i) memset(array [i], 0, N * sizeof (int)); return array; } |
Compliant
...
Solution (sizeof
)
This compliant solution prevents sizeof
wrapping by detecting the condition before it occurs and avoiding the subsequent computation when the condition is detected.
...