Main Content

AUTOSAR C++14 Rule A18-1-1

C-style arrays shall not be used

Description

Rule Definition

C-style arrays shall not be used.

Rationale

A C-style array is an array that is not wrapped in a class such as std::array when the array is declared. You can lose information about the size of a C-style array. For instance, an array that you pass to a function decays to a pointer to the first element of the array. This can lead to unsafe and difficult to maintain code.

The AUTOSAR standard allows declarations of static constexpr data members of a C-style array type. For example, this declaration is compliant.

class A
{
  public:
    static constexpr std::uint8_t array[] {0, 1, 2}; // Compliant by exception
};

Polyspace Implementation

The rule checker does not flag C-style array arguments in function declarations because the rule violation still exists if you fix the function declaration and not the definition. A function might be declared in your code and defined in a library that you cannot access. The checker flags C-style array arguments in function definitions. For instance, in this code snippet, the checker flags the argument of foo but not the argument of bar.

extern void bar(char arg[]); //Declaration, checker raises no rule violation
int foo(char arg[]) // Definition, checker raises a rule violation
{
    return sizeof(arg); //Returns size of pointer, not size of array
}
void baz()
{
    char value[10]; //C-style array, checker raises a rule violation
    assert(sizeof(value) == foo(value));
}
The checker raises a flag on arg in the definition of foo even when there is no explicit C-style array definition for the argument. For example, declaring char* value; instead of char value[10]; in baz() would still result in a rule violation on the argument of foo.

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

#include <array>

void func()
{

    const std::uint8_t size = 10;
    std::int32_t a1[size]; //non-compliant
    std::array<std::int32_t, size> a2; //compliant

}

In this example, the rule is violated when you declare C-style array a1. To declare fixed-size stack-allocated arrays, use std:array instead.

Check Information

Group: 18 Language Support Library
Category: Required, Automated

Version History

Introduced in R2019b