...
When compiled for Windows (x86), the output of this program is:
Size of struct: 16 bytes
Non-Compliant Coding Example
This non-compliant example demonstrates the incorrect way to declare a triangular array of integers.
| Code Block | ||
|---|---|---|
| ||
/* assuming 32-bit pointer, 32-bit integer */
int i;
int** triarray = calloc(100, 4);
for (i = 0; i < 100; i++)
triarray[i] = calloc(i, 4);
|
Compliant Solution
The above example can be fixed by replacing the hard-coded value 4 with the actual size of the datatype as represented on the target platform. Remember to check the return value of the memory allocation routines.
| Code Block | ||
|---|---|---|
| ||
int i;
int** triarray = calloc(100, sizeof(int*));
if (!triarray)
{ /* perform cleanup, return error */ }
for (i = 0; i < 100; i++) {
triarray[i] = calloc(i, sizeof(int));
if (!triarray[i])
{ /* perform cleanup, return error */ }
}
|
Risk Assessment
If non-compliant code is ported to a different platform, it could introduce a heap or stack overflow vulnerability.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
EXPxx-A | 3 (high) | 1 (unlikely) | 2 (medium) | P6 | L2 |
References
| Wiki Markup |
|---|
\[[ISO/IEC 9899-1999|cplusplus:AA. C++ References#ISO/IEC 9899-1999]\] Section 6.2.6, "Representations of types", and Section 6.5.3.4, "The sizeof operator" |