...
It should be noted that only one object is created per CL -- even if the CL appears in a loop and has dynamic initializers (6.5.2.5.16). This can lead to incorrect use, as demonstrated below.
Noncompliant Code Example
Wiki Markup |
---|
In the following example, an array of pointers is filled with what appear to addresses of distinct INT_STRUCT objects, one for each integer in the range \[0,MAX_INTS-1\]: |
...
This is contrary to the intuitive expected result, which is that the integers 0 through MAX_INTS-1 would be printed in order.
Compliant Solution
This compliant solution uses an array of structures rather than an array of pointers. That way, an actual copy of each INT_STRUCT (rather than a pointer to the object) is stored.
Code Block | ||
---|---|---|
| ||
typedef struct INT_STRUCT{ int x; } INT_STRUCT; #define MAX_INTS 10 int count(){ int i; INT_STRUCT ints[MAX_INTS]; for(i=0;i<MAX_INTS;i++) ints[i] = (INT_STRUCT){i}; for(i=0;i<MAX_INTS;i++) printf("%d\n",ints[i].x); } |
Risk Assessment
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL90-C | low | unlikely | low | P3 | L3 |
References
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|../display/seccode/AA.+References#AA.References-ISO%2FIEC98991999||||||\||]\] Section 6.5.2.5 (Compound Literals) |