...
| Code Block |
|---|
|
#include <stdio.h>
struct X { int a[6]; };
struct X addressee(void) {
struct X result = { { 1, 2, 3, 4, 5, 6 } };
return result;
}
int main(void) {
struct X my_x = addressee();
printf("%x", ++(my_x.a[0]));
return 0;
}
|
Noncompliant Code Example
This noncompliant code example attempts to save a pointer to an array that is part of a struct that is returned by a function call. Consequently, the array has temporary lifetime, and using the pointer to it outside of the full expression is undefined behavior in both C99 and C11.
| Code Block |
|---|
|
#include <stdio.h>
struct X { int a[6]; };
struct X addressee(void) {
struct X result = { { 1, 2, 3, 4, 5, 6 } };
return result;
}
int main(void) {
int *my_a = addressee().a;
printf("%x", my_a[0]);
return 0;
}
|
Compliant Solution
This compliant solution stores the structure returned by the call to addressee() as my_x before saving a pointer to its array member. When the pointer is used, its lifetime is no longer temporary but matches the lifetime of the block in main().
| Code Block |
|---|
|
#include <stdio.h>
struct X { int a[6]; };
struct X addressee(void) {
struct X result = { { 1, 2, 3, 4, 5, 6 } };
return result;
}
int main(void) {
struct X my_x = addressee();
int *my_a = my_x.a;
printf("%x", my_a[0]);
return 0;
}
|
Risk Assessment
Attempting to modify an array or access it after its lifetime expires may result in erroneous program behavior.
...