Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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\]:

Code Block
bgColor#FFCCCC
borderStylesolid

#include <stdio.h>

typedef struct INT_STRUCT{
  int x;
} INT_STRUCT;

#define MAX_INTS 10
int count(main(int argc,char **argv){
  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);
}

...

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
bgColor#CCCCFF
borderStylesolid

#include <stdio.h>

typedef struct INT_STRUCT{
  int x;
} INT_STRUCT;

#define MAX_INTS 10

int count(main(int argc,char** argv){
  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 DCL21-C

low

unlikely

medium low

P4 P3

L3

References

Wiki Markup
\[[ISO/IEC  9899:1999&#124;..|https://www.securecoding.cert.org/confluence/display/seccode/AA.+References#AA.References-ISO%2FIEC98991999&#124;&#124;&#124;&#124;&#124;&#124;\||]\] Section 6.5.2.5 (Compound Literals)