...
C functions may not return entire arrays; however, functions can return a pointer to an array or a struct or union that contain contains arrays. Consequently, if a function call 's return value contains returns by value a struct or union containing an array, that array should never be modified do not modify those arrays within the expression containing the function call. Do not access an array returned by a function after the next sequence point or after the evaluation of the containing full expression or full declarator ends.
...
This noncompliant code example conforms with to the C11 standard; however, it fails to conform with to C99. If compiled with a C99-conforming implementation, this code demonstrates has undefined behavior because the sequence point preceding the call to printf() comes between the call and the access by printf() of the string in the returned object:.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h>
struct X { char a[8]; };
struct X salutation() {
struct X result = { "Hello" };
return result;
}
struct X addressee() {
struct X result = { "world" };
return result;
}
int main(void) {
printf("%s, %s!\n", salutation().a, addressee().a);
return 0;
}
|
...
This compliant solution stores the structures returned by the call to addressee() before calling the printf() function. Consequently, this program conforms with to both C99 and C11.
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h>
struct X { char a[8]; };
struct X salutation() {
struct X result = { "Hello" };
return result;
}
struct X addressee(void) {
struct X result = { "world" };
return result;
}
int main(void) {
struct X my_salutation = salutation();
struct X my_addressee = addressee();
printf("%s, %s!\n", my_salutation.a, my_addressee.a);
return 0;
}
|
...
Risk Assessment
Attempting to modify an array or access it after its lifetime expires may result in erroneous program behavior.
...
Bibliography
| [ISO/IEC 9899:2011] | Subclause 6.2.4, "Storage Durations of Objects" |
...