Do not access or modify the result of a function call after a subsequent sequence point. According to C99 Section 6.5.2.2, "Function calls,"
If an attempt is made to modify the result of a function call or to access it after the next sequence point, the behavior is undefined.
Non-Compliant Code Example
In C, the lifetime of a return value ends at the next sequence point.
#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;
}
This program has undefined behavior because there is a sequence point before printf() is called, and printf() accesses the result of the call to addressee().
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.
Compliant Solution
This compliant solution does not have undefined behavior because the structure returned by the call to addressee() is stored as the variable my_x before calling the printf() function.
#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, %s!\n", my_x.a);
return 0;
}
Risk Assessment
Attempting to access or modify the result of a function call after a subsequent sequence point may result in unexpected and perhaps unintended program behavior.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
EXP35-C |
1 (low) |
1 (unlikely) |
3 (low) |
P3 |
L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[ISO/IEC 9899-1999]] Section 6.5.2.2, "Function calls"
[[ISO/IEC PDTR 24772]] "DCM Dangling references to stack frames" and "SAM Side-effects and order of evaluation"
EXP34-C. Ensure a null pointer is not dereferenced 03. Expressions (EXP) EXP36-C. Do not convert pointers into more strictly aligned pointer types