[Note: This is reposted from https://softwareengineering.stackexchange.com/q/369604/126197, where for some reason this question got immediately downvoted. Twice. Clearly there's more love over here!]
Here's a bit of code paraphrased from a vendor's example.
I've looked for authoritative documentation on passing stack-allocated structures by value, but haven't found the definitive word. In a nutshell: Does C99 guarantee this to be safe?
typedef struct {
int32_t upper;
int32_t lower;
} boundaries_t;
static boundaries_t calibrate() {
boundaries_t boundaries; // struct allocated on stack
boundaries.upper = getUpper();
boundaries.lower = getLower();
return boundaries; // return struct by value
}
int main() {
boundaries_t b;
b = calibrate();
// do stuff with b
...
}
Note that calibrate()
allocates the boundaries
struct on the stack and then returns it by value.
If the compiler can guarantee that the stack frame for calibrate()
will be intact at the time of the assignment to b
, then all is well. Perhaps that's part of the contract in C99's pass-by-value?
(Context: my world is embedded systems where pass-by-value is rarely seen. I do know that returning a pointer from a stack-allocated structure is a recipe for disaster, but this pass-by-value stuff feels alien.)