Versions Compared

Key

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

...

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.

C forbids functions from to returning arrays; however it is possible to return structs or unions that contain arrays.

...

  1. In C, the lifetime of a return value ends at the next sequence point. Consequently by the time printf() is called, the struct returned by the addressee() call is no longer considered valid, and may have been overwritten.
  2. C function arguments are passed by value. As a result, copies are made of all objects generated by the arguments. For example, a copy is made of the pointer to "Hello, %s!\n". Under most circumstances, these copies protect one from the effects of sequence points described earlier.
  3. Finally, C implicitly converts arrays to pointers when passing them as function arguments. This means that in the previous point, a copy is made of the pointer to the addresee().a array, and that pointer copy is passed to printf(). But the array data itself is not copied, and may no longer exists exist when printf() is called.

Consequently when printf() tries to dereference the pointer passed as its 2nd argument, it will likely find garbage.

...

Compliant Solution

This compliant solution does not have undefined behavior because store the structure returned by the call to addressee() is stored as the variable my_x before calling the printf() function.

...

Attempting to access or modify an array inside the result of within a function call after a subsequent sequence point may result in unexpected and perhaps unintended program behavior.

...