0

I have this snippet :

func(int **t)
{
        int q = 40;
        *t = &q;
}

int main()
{
        int a = 20;
        int *p = &a;

        func(&p);
        printf("%d\n", *p);
}

This program outputs 40 , since pointer p is pointing to address of q instead of a, after *t = &q.

But once we returned from func(int **t), q is no longer exist but still *p gives 40, how ?

Milan
  • 1,447
  • 5
  • 19
  • 27
  • 2
    Because the memory had not yet been re-used. Try calling some other function between the two calls. – Weather Vane Nov 10 '21 at 13:58
  • 2
    You are right. You have there an example of UB. The reason that you get 40 is that the value is still floating around, so luck, basically. (I mean, that the value is still there in that memory location, not yet overwritten, as @WeatherVane more clearly put it.) – Dúthomhas Nov 10 '21 at 13:58
  • 1
    Undefined behavior is undefined ¯\\_(ツ)_/¯ – Jonathon Reinhart Nov 10 '21 at 13:59
  • Ok, what is right way to point p to q in this case from same function ? – Milan Nov 10 '21 at 14:03
  • 1
    That memory address *does* exist: it is the ownership that you lose. Unless you put **`static`** `int q = 40;` – Weather Vane Nov 10 '21 at 14:03
  • 1
    @Milan Make `q` static (or threadlocal). Otherwise don’t do it. – Dúthomhas Nov 10 '21 at 14:05
  • @Milan there is no safe way to "point p to q', or rather, there is no safe way to dereference the pointer after `q` goes out of scope. As @Dúthomhas said, if the variable is `static` then it will persist after the function returns. That's your only option, I think – Tim Randall Nov 10 '21 at 14:05

0 Answers0