MISRA C++:2023 Rule 7.11.2
Description
Rule Definition
An array passed as a function argument shall not decay to a pointer.
Rationale
When you pass an array as an argument to a function, the array decays to a pointer in the function scope. After this decay, the bounds of the array are no longer known in the function scope and bounds checking is not possible. For instance, consider this code:
void bar(int array[10]); void foo() { int array[8]; bar(array); //array decays to pointer }
bar()
is called from the function
foo()
, its argument immediately decays to a pointer. Calling
bar()
with a nine-element array compiles without any errors. The
current definition of bar()
cannot check the bounds of the input
array, which can result in an array index out of bounds error and undefined
behavior.Avoid passing arrays as function parameters without preserving their bounds. You can use several strategies to preserve the dimensionality of a passed pointer:
Declare functions to accepts arrays of specific dimensions:
Here,void bar(int (&array)[10]); //... int array1[10]; int array2[11]; //... bar(array1); bar(array2); //Compile fail
bar()
expects a reference to an array of 11 elements. With this definition, callingbar()
with anarray
of incorrect size causes a compilation fail.Implement functions as templates that accepts arrays of different size. The dimensionality of the array is preserved in the function scope while maintaining the flexibility of calling the function with arrays of arbitrary size.
template<size_t numel> void bar(int (&array)[numel]); //array size automatically deduced //... int array1[10]; int array2 [11]; //... bar(array1); bar(array2);
Instead of using a C-style array, consider using containers from the standard template library (STL). These containers preserve their bounds when passed as arguments to functions.
If you are using C++20, consider wrapping the array in an
std::span
object. Otherwise, consider wrapping the array in a class similar tostd::span
. See std::span.
As an exception, it is not a violation of this rule to pass string literals to
functions with a char*
parameter. String literals are null-terminated
and the null-termination allows for bounds checking when string literals are passed to
functions as char*
arguments.
Polyspace Implementation
Polyspace® reports a violation of this rule if a C-style array is passed to a function. Polyspace does not report a violation if you pass string literals to functions.
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
Check Information
Group: Standard Conversions |
Category: Required |
Version History
Introduced in R2024b