0
void f(int **pp)
{
   int q = 10;
  *pp = &q;
}

int main()
{
  int a = 5;
  int *p = &a;
  f(&p);
  printf("%d", *p);
  return 0;
}

On compilation, this code returns 0 as the stack variable qvanishes after stack frame is removed .

But, as being a dangling pointer, I guess it may also return some garbage values.

But, I compiled it on different compilers, all of them return 0. Why is that so ?

Barry
  • 9
  • 1
  • 5

2 Answers2

4

This is so because of undefined behavior.

There is no definition or concept (for example, range of values which can be called garbage or alike) of "garbage" value in regards to C standard. The behaviour is undefined, so anything could happen. There is no guarantee that after invoking the UB, the program would (or would not, for that matter) continue execution to produce (or not to produce) any output, at all.

Related, quoting C11, chapter §3.4.3, undefined behavior

  • 1 undefined behavior

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

  • 2 NOTE

Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

In this case, you assign the memory location from a called stack frame to p in f. When you call printf, the stack frame which was prior used by f is now used by printf, and in your case it is overwritten by a zero.

The problem is, that you assign a later invalid memory location in f, since you must not access variables of a function after the function returned.

Rudi
  • 19,366
  • 3
  • 55
  • 77