This diagnostic rule is based on the MISRA (Motor Industry Software Reliability Association) manual for software development.
This rule only applies to C. Declaring variable-length arrays can lead to a stack overflow and potential vulnerabilities in the program.
Look at the example:
void foo(size_t n)
{
int arr[n];
// ....
}
Transmission of large number 'n' can lead to a stack overflow as the array will become too large and take up more memory than it really is.
The most logical way is to limit the size of the array:
#define MAX_SIZE 128
void foo(size_t n)
{
size_t size = n > MAX_SIZE ? MAX_SIZE : n;
int arr[size];
if (size < n) // error
// ....
}
However, in this case it is better to use a constant to simplify the logic of the program:
#define SIZE 128
void foo()
{
int arr[size];
// ....
}
This will also help to avoid VLA-connected problems like calculating 'sizeof' on such arrays and passing them to other functions.
This diagnostic is classified as:
|