Main Content

MISRA C++:2008 Rule 3-1-3

When an array is declared, its size shall either be stated explicitly or defined implicitly by initialization

Description

Rule Definition

When an array is declared, its size shall either be stated explicitly or defined implicitly by initialization.

Rationale

Declaring an array with external linkage without specifying its size and then attempting to access elements of the array can result in an array index out of bounds error. To reduce the possibility of such errors, specify the size of an array in its declaration.

Polyspace Implementation

Polyspace® reports a violation of this rule if all of these conditions are true:

  • You declare an extern array.

  • The array is not initialized.

  • The number of elements for the array is not explicitly stated.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

int array[10];  
extern int array2[]; //Noncompliant
int array3[]= {0,1,2};
extern int array4[10];

In the declaration of array2, the array size is unspecified.

In this example, the size of the array first_scores is implicitly defined by initialization. The size of the array second_scores is explicitly defined using the [] operator. Polyspace does not report a rule violation.

The size of the array mean_scores is declared neither implicitly nor explicitly. Polyspace reports a violation.

int first_scores [] = { 89, 100, 84, 48,  93 }; //Compliant
int second_scores [5]; //Compliant
extern int mean_scores []; //Noncompliant

int * test_mean (int factor) {
    for (int i = 0; i < 5; ++i){
        second_scores[i] = i * factor;
        mean_scores[i] = (first_scores[i] + second_scores[i]) / 2;
    }
    return mean_scores;
}

Check Information

Group: Basic Concepts
Category: Required

Version History

Introduced in R2013b