...
This applies to all array parameters, even if the parameter declaration contains an index.
Compliant Solution
In this compliant solution, the size of the array is determined inside the block in which it is declared and passed as an argument to the function.
...
| Wiki Markup |
|---|
This {{sizeof(array) / sizeof(array\[0\])}} idiom will succeed provided the original definition of {{array}} is visible. |
Noncompliant Code Example
In this noncompliant code example, the sizeof a does not equal 100 * sizeof(int). This is because the sizeof operator, when applied to a parameter declared to have array or function type, yields the size of the adjusted (pointer) type, even if the parameter declaration specifies a length.
| Code Block | ||
|---|---|---|
| ||
void clear(int a[100]) {
memset(a, 0, sizeof a); /* error */
}
int main(void) {
int b[100];
clear(b);
assert(b[50]==0); /* may fail */
return 0;
}
|
Compliant Solution
In this compliant solution, the size is specified using the expression 100 * sizeof(int).
| Code Block | ||
|---|---|---|
| ||
void clear(int a[100]) {
memset(a, 0, 100 * sizeof(int));
}
int main(void) {
int b[100];
clear(b);
assert(b[50]==0); /* may fail */
return 0;
}
|
Risk Assessment
Incorrectly using the sizeof operator to determine the size of an array can result in a buffer overflow, allowing the execution of arbitrary code.
...