...
The size implied by an initialization literal is usually specified by the number of elements,
Code Block |
---|
int array[] = {1, 2, 3}; /* 3-element array */
|
but it is also possible to use designators to initialize array elements in a noncontiguous fashion. Subclause 6.7.9, Example 12, of the C Standard [ISO/AA. Bibliography#ISO-IEC 9899:-2011] states:
Space can be "allocated" from both ends of an array by using a single designator:
int a[MAX] = { 1, 3, 5, 7, 9, [MAX-5] = 8, 6, 4, 2, 0 }; Code Block In the above, if
MAX
is greater than ten, there will be some zero-valued elements in the middle; if it is less than ten, some of the values provided by the first five initializers will be overridden by the second five.
...
Code Block | ||||
---|---|---|---|---|
| ||||
int a[3] = {1, 2, 3, 4};
| ||||
The size of the array a
is 3, although the size of the initialization is 4. The last element of the initialization (4
) is ignored. Most compilers will diagnose this error.
...
Code Block | ||||
---|---|---|---|---|
| ||||
int a[] = {1, 2, 3, 4};
| ||||
Compliant Solution
This compliant solution explicitly specifies the array bound:
Code Block | ||||
---|---|---|---|---|
| ||||
int a[4] = {1, 2, 3, 4};
| ||||
Explicitly specifying the array bound, although it is implicitly defined by an initializer, allows a compiler or other static analysis tool to issue a diagnostic if these values do not agree.
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
|
|
| |||||||
| CC2.ARR02 | Fully implemented | |||||||
| 127 S | Fully implemented | |||||||
PRQA QA-C |
| 0688,3674,3684, 678 | Fully implemented |
...
SEI CERT C++ Coding Standard | CTR02-CPP. Explicitly specify array bounds, even if implicitly defined by an initializer |
MITRE CWE | CWE-665, Incorrect or incomplete initialization |
MISRA C:2012AA. Bibliography#MISRA 12 | Rule 8.11 (advisory), Rule 9.5 (required) |
Bibliography
[ISO/AA. Bibliography#ISO-IEC 9899:-2011] | Subclause 6.7.9, "Initialization" |
...