I know that I can't return a locally declared array from a function, because the array lives in the function's stack space and after returning, the pointer will dangle.
I.e. this is invalid
int* test() {
int x[3] = {1,2,3};
return x;
}
main() {
int* x = test();
}
Therefore I'm nervous about returning structs which contain arrays; since they are just made part of the struct's contiguous memory space, are copied on return.
I.e. this is totally fine
typedef struct Container {
int arr[3][3];
} Container;
Container getContainer() {
Container c = {.arr = {{1,2,3}, {4,5,6}, {7,8,9}} };
return c;
}
int main() {
Container c = getContainer();
// c.arr is "deep copied" to main's stack space
}
Still, I have a deep instinct to instead do do something like
void populateContainer(Container* c) {
int arr[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
memcpy(c->arr, arr, 3*3 * sizeof(arr));
}
int main() {
Container c;
populateContainer(&c);
}
So my question is, should I just trust that the array will always be safely copied-by-value when the struct is returned, and avoid the latter pattern? I'm always using the C99
standard. Are there compilers which wouldn't respect this, and for which I should use the uglier-but-seemingly-safer address-passing pattern?