Main Content

Variable length array with non-positive size

Size of variable-length array is zero or negative

Description

This defect occurs when size of a variable-length array is zero or negative.

Risk

If the size of a variable-length array is zero or negative, unexpected behavior can occur, such as stack overflow.

Fix

When you declare a variable-length array as a local variable in a function:

  • If you use a function parameter as the array size, check that the parameter is positive.

  • If you use the result of a computation on a function parameter as the array size, check that the result is positive.

You can place a test for positive value either before the function call or the array declaration in the function body.

Examples

expand all

int input(void);

void add_scalar(int n, int m) {
    int r=0;
    int arr[m][n];
    for (int i=0; i<m; i++) {
        for (int j=0; j<n; j++) {
            arr[i][j] = input();
            r += arr[i][j];
        }
    }
}

void main() {
    add_scalar(2,2);
    add_scalar(-1,2);
    add_scalar(2,0);
}

In this example, the second and third calls to add_scalar result in a negative and zero size of arr.

Correction — Make Array Size Positive

One possible correction is fix or remove calls that result in a nonpositive array size.

Result Information

Group: Programming
Language: C | C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: NON_POSITIVE_VLA_SIZE
Impact: High

Version History

Introduced in R2015b