Main Content

MISRA C:2023 Rule 17.5

The function argument corresponding to a parameter declared to have an array type shall have an appropriate number of elements

Since R2024a

Description

Rule Definition

The function argument corresponding to a parameter declared to have an array type shall have an appropriate number of elements.

Rationale

If you use an array declarator for a function parameter instead of a pointer, the function interface is clearer because you can state the minimum expected array size. If you do not state a size, the expectation is that the function can handle an array of any size. In such cases, the size value is typically another parameter of the function, or the array is terminated with a sentinel value.

However, it is legal in C to specify an array size but pass an array of smaller size. This rule prevents you from passing an array of size smaller than the size you declared.

Polyspace Implementation

The rule checker reports a violation if a function declared with an array parameter of a certain size is invoked with a smaller array. Note that:

  • If a function has multiple array parameters with specified sizes and you pass smaller arrays for each parameter, the violation is reported only once.

  • The checker reports a violation only if you pass an array directly to a function. Instead, if you pass a pointer that points to the array, the checker does not report a violation.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

void func(int arr[4]);

int main() {
    int arrSmall[3] = {1,2,3};
    int arr[4] = {1,2,3,4};
    int arrLarge[5] ={1,2,3,4,5};
    
    func(arrSmall);      /* Non-compliant */
    func(arr);           /* Compliant */
    func(arrLarge);      /* Compliant */
    
    return 0;
}

In this example, the rule is violated when arrSmall, which has size 3, is passed to func, which expects at least 4 elements.

Check Information

Group: Functions
Category: Required
AGC Category: Readability

Version History

Introduced in R2024a