You're calling this function twice:
myStruct init(int x){
myStruct s;
s.field = &x;
return s;
}
On both calls, the variable (or parameter) x
is allocated, but not valid anymore when the function returns. You've stored the address of a local variable, and since you're using the same function, the local variable address is the same the second time, which explains the "magic" (which is still undefined behaviour but most compilers using stack for auto variables will yield the same result)
Unfortunately compilers aren't smart enough to detect that you're storing an address of a local variables. They usually trigger warnings when you're returning an address on a local (it's easier to detect).
For instance if you call printf
, you will get not 1 or 2 but complete garbage as the parameter memory won't be organized the same way as your function.
A clean way would be to allocate dynamic memory:
s.field = malloc(sizeof(*s.field)); // this memory persists even after the end of "init"
*s.field = x; // copying the value, not the address
Of course it needs deallocation when structure isn't used.