...
| 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);
/* ... */
}
|
Footnote 103 in section subclause 6.5.3.4 of the C Standard [ISO/IEC 9899:2011] explains:
When applied to a parameter declared to have array or function type, the
sizeofoperator yields the size of the adjusted (pointer) type.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
enum {ARR_LEN = 100};
void clear(int a[ARR_LEN]) {
memset(a, 0, sizeof(a)); /* errorError */
}
int main(void) {
int b[ARR_LEN];
clear(b);
assert(b[ARR_LEN / 2]==0); /* mayMay fail */
return 0;
}
|
Compliant Solution
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
enum {ARR_LEN = 100};
void clear(int a[], size_t len) {
memset(a, 0, len * sizeof(int));
}
int main(void) {
int b[ARR_LEN];
clear(b, ARR_LEN);
assert(b[ARR_LEN / 2]==0); /* cannotCannot fail */
return 0;
}
|
Risk Assessment
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
|
| Can detect violations of the recommendation but cannot distinguish between incomplete array declarations and pointer declarations | |||||||
| 401 S | Partially implemented | |||||||
|
|
|
...
| CERT C++ Secure Coding Standard | ARR01-CPP. Do not apply the sizeof operator to a pointer when taking the size of an array |
| MITRE CWE | CWE-467, Use of sizeof() on a pointer type |
| ISO/IEC TS 17961 (Draft) | Taking the size of a pointer to determine the size of the pointed-to type [sizeofptr] |
...
| [Drepper 2006] | Section 2.1.1, "Respecting Memory Bounds" |
| [ISO/IEC 9899:2011] | Section Subclause 6.5.3.4, "The sizeof and _Alignof Operators" |
...