Versions Compared

Key

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

...

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

struct X { char a[6]; };

struct X addressee() {
  struct X result = { "world" };
  return result;
}

int main(void) {
  printf("Hello, %s!\n", addressee().a);
  return 0;
}

Because This program has undefined behavior because there is a sequence point after the call to addresseebefore printf() and before is called, and printf() accesses the result of the call to printfaddressee(), this program has
undefined behavior.

Implementation Details

This code compiles cleanly and runs without error under Microsoft Visual C++ Version 8.0. On gcc version 4.1, the program compiles with a warning when the -Wall switch is used and execution on Linux results in a segmentation fault.

...

This compliant solution does not have undefined behavior because the reference to the returned value is evaluated before the subsequent sequence pointstructure returned by the call to addressee() is stored is stored as the variable my_x before calling the printf() function.

Code Block
bgColor#ccccff
#include <stdio.h>

struct X { char a[6]; };

struct X addressee() {
  struct X result = { "world" };
  return result;
}

int main(void) {
  struct X my_x = addressee();
  printf("Hello, %c%s!\n", addressee()my_x.a[rand() % 5]);
  return 0;
}

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP34-C

1 (low)

1 (low)

3 (medium)

P3

L3

Examples of Search for vulnerabilities resulting from the violation of this rule can be found on the CERT website.

References

Wiki Markup
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]] Section 6.5.2.2, "Function calls"