So I think that what I got from this post is that it is UB or at least not a good idea to return pointers to locally defined variables, and in fact my compiler gives warning if I do this, however if I wrap the pointer in a struct then the warning no longer shows. Is it still UB or is there something different with structs that makes this OK. I'm using GCC 6.3.0 with -Wall.
Here is an example:
#include <stdio.h>
struct wrapper{
int *ptr;
};
struct wrapper foo(){
int a = 5;
struct wrapper new_wrapper = {&a};
return new_wrapper;
}
int main(){
printf("%d", *foo().ptr); //prints 5, but will it theoretically always do so?
return 0;
}