0

I found this question, I should tell what will be the output.

  #include <stdio.h>
    int main()
    {
        int i = 10;
        int *p = &i;
        foo(&p);
        printf("%d ", *p);
        printf("%d ", *p);
    }
    void foo(int **const p)
    {
        int j = 11;
        *p = &j;
        printf("%d ", **p);
    }

I think it shuold be 11 11 11. The answer is 11 11 unefined. I checked with debugger and I found that the printf returns 3, and after the second print p point to that value 3. I don't know why it happens. If someone can explain that would be great. thanks.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
ni al
  • 11
  • 1
  • 4
    Using `*p` in `main` after `foo` returns is undefined behavior, because `p` pointed to `j` which is now out of scope. It's not very interesting to ask why you got some particular set of garbage outputs and not some other particular set. Just fix your code. – Nate Eldredge Dec 24 '20 at 18:44
  • See also https://stackoverflow.com/questions/4570366/how-to-access-a-local-variable-from-a-different-function-using-pointers – 12431234123412341234123 Dec 24 '20 at 18:47
  • 1
    The solution you found is both right and wrong. Since the behavior is undefined, the output *could* be `11 11 unefined`. It could also be `11 11 11` or `11 39082094 -329848` or `11 halibut bream` or `11 Segmentation fault`. – Nate Eldredge Dec 24 '20 at 18:47
  • It might be possible to determine what the actual output would be *if* you know the precise details of the compiler, compilation options, memory layout, machine architecture, and operating system. But if that's what the question is aiming at, it would need way more information to be given. – Nate Eldredge Dec 24 '20 at 18:49
  • 1
    Note that @NateEldredge's list of possible behavior is incomplete. It is not necessary for `11` to be output at all. – William Pursell Dec 24 '20 at 19:05

1 Answers1

0

That happens because you're assigning p to the address of a local variable, so the behavior is actually undefined both for the second and the third printf.

Once the function reaches the end, all its local variables fall out of scope. The memory they used is no longer reserved, so p points to an address which may still contain the value 11, but it may have been overwritten as well, as is the case on your computer (on mine I get 11 every time, but it's only a fortuity).

To make sure the value isn't lost, you could declare j as a static or global variable or allocate it with an *alloc function.

MDXZ
  • 160
  • 12