In foo() and foo2() you are returning pointers to local variables. These locals have automatic storage and it is undefined behavior to use a pointer to them once they go out of scope. Therefor p and p2 contain nothing useful. It might work, it might not.
I can’t understand your question very well, so I hope I got it all.
13
solved What happened to local pointer? [closed]