-1

I need to analyze the output of the following program:

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

I know nobody actually writes this way, but nonetheless. I expected it to output something like 11 [garbage] [garbage], only to find the answer is 11 11 [undefined value]. I decided to spin a bit.

#include "stdio.h"
void foo(int **p)
{
    int j = 11;
    *p = &j;
    printf("1:-");
    printf("%d-", **p);
}
int main()
{
    int i = 10;
    int *p = &i;
    foo(&p);
    /* printf("2:-"); */ 
    printf("%d-", *p);
    printf("3:-");
    printf("%d-", *p);
}

This would give 1:-11-11-3:-0- on my platform (macOS 10.12.2, tested both on Apple LLVM version 8.0.0 (clang-800.0.42.1) and Homebrew gcc 6.2.0).

And if I un-comment that printf("2:-"); line I would get 1:-11-2:-0-3:-0-. The second call prints p differently. Again both compilers yield same result.

Here are my questions:

  1. Is the original answer even correct? And how is it (in)correct?

  2. Why and how does that commented call to printf changes the content of p? Or am I missing the point?

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143
Virgil Ming
  • 549
  • 4
  • 12

1 Answers1

1

The pointer's value is indeterminate and referring to that object invokes undefined behavior, according to 6.2.4p2 Storage durations of objects:

[...] If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to reaches the end of its lifetime.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104