...
Noncompliant Code Example
In this noncompliant code example, the function {{Wiki Markup clear()}} zeros the elements in an array. The function has one parameter declared as {{int array\[\]}} and is passed a static array consisting of 12 {{int}} as the argument. The function {{clear()}} uses the idiom {{sizeof(array) / sizeof(array\[0\])}} to determine the number of elements in the array. However, {{array}} has a pointer type because it is a parameter. As a result, {{sizeof(array)}} is equal to the {{sizeof(int \ *)}}. For example, on an architecture (such as IA-32) where the {{sizeof(int) == 4}} and the {{sizeof(int *) == 4}}, the expression {{sizeof(array) / sizeof(array\[0\])}} evaluates to 1, regardless of the length of the array passed, leaving the rest of the array unaffected.
| Code Block | ||||
|---|---|---|---|---|
| ||||
void clear(int array[]) {
for (size_t i = 0; i < sizeof(array) / sizeof(array[0]); ++i) {
array[i] = 0;
}
}
void dowork(void) {
int dis[12];
clear(dis);
/* ... */
}
|
The footnote in Section 6.5.3.4 of the C Standard \[ [ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999] \] explains this:Wiki Markup
When applied to a parameter declared to have array or function type, the
sizeofoperator yields the size of the adjusted (pointer) type . . . .
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
void clear(int array[], size_t len) {
for (size_t i = 0; i < len; i++) {
array[i] = 0;
}
}
void dowork(void) {
int dis[12];
clear(dis, sizeof(dis) / sizeof(dis[0]));
/* ... */
}
|
This {{Wiki Markup sizeof(array) / sizeof(array\[0\])}} idiom will succeed provided the original definition of {{array}} is visible.
Noncompliant Code Example
...
Tool | Version | Checker | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
|
| ||||||||||||
|
|
|
| ||||||||||||
|
|
|
|
...
MITRE CWE: CWE-467, "Use of sizeof() on a Pointer Type"
Bibliography
...
\[[Drepper 2006|AA. Bibliography#Drepper 06]\] Section 2.1.1, "Respecting Memory Bounds"
...
06. Arrays (ARR) ARR02-C. Explicitly specify array bounds, even if implicitly defined by an initializer