C99 Section 6.5.2.2 says [[ISO/IEC 9899:1999]],
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.
As a result, the result of a function call after a subsequent access point must never be accessed or modified.
Non-Compliant Code Example
The following non-compliant code attempts to retrieve a field from a struct that is returned by a function call.
#include <stdio.h>
struct X { char a[6]; };
struct X addressee(void) {
struct X result = { "world" };
return result;
}
int main(void) {
printf("Hello, %s!\n", addressee().a);
return 0;
}
In C, the lifetime of a return value ends at the next sequence point. This program has undefined behavior because despite a sequence point before printf() is called, there is an attempt to to access the return value of addressee().
Implementation Details
This code compiles cleanly and runs without error under Microsoft Visual C++ Version 8.0. On GCC Compiler 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(void) {
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 |
low |
probable |
medium |
P4 |
L3 |
Automated Detection
Splint Version 3.1.1 can detect violations of this rule.
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