Versions Compared

Key

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

Section Subclause 6.5.2.5 of the C Standard [ISO/IEC 9899:2011] defines a compound literal as

...

following initialization, the int pointer ip contains the address of an unnamed object of type int[4], allocated on the stack. Once func returns, any attempts to access this object will produce undefined behavior.

Note that only one object is created per compound literal—even if the compound literal appears in a loop and has dynamic initializers.

...

Code Block
bgColor#FFCCCC
langc
#include <stdio.h>

typedef struct int_struct {
  int x;
} int_struct;

#define MAX_INTS 10

int main(void){
  size_t 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);
  }
 
  return 0;
}

However, only one int_struct object is created. At each iteration of the first loop, the x member of this object is set equal to the current value of the loop counter i. Therefore, just before the first loop terminates, the value of the x member is MAX_INTS - 1.

...

Code Block
bgColor#CCCCFF
borderStylesolid
langc
#include <stdio.h>

typedef struct int_struct {
  int x;
} int_struct;

#define MAX_INTS 10

int main(void){
  size_t 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);
  }
 
  return 0;
}

Risk Assessment

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

DCL21-C

low

Low

unlikely

Unlikely

medium

Medium

P2

L3

Automated Detection

Tool

Version

Checker

Description

Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC-DCL21
Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C1054, C3217

Bibliography

[ISO/IEC 9899:2011]
Section
Subclause 6.5.2.5, "Compound Literals"

...


...

Image Modified Image Modified Image Modified