0

I want to modify my pointer's value in a function but I don't get why this example works.

#include<stdio.h>
void foo (int **p);
int main()
{
    int i=97;
    int *p = &i;
    foo(&p);
    printf("%d",*p);
    return 0;
}

void foo (int **p)
{
    int j=2;
    *p = &j;
    printf("%d",**p);
}

The output is 2 2 but how can it be possible if j doesn't exist anymore in the main? what does p point to? I would have expected that in the second time I printed the value of p(in the main) there will be garbage.

  • 3
    Undefined behavior is undefined. Just because it *might* be garbage doesn't mean it *must* be garbage. See [this question](https://stackoverflow.com/q/19559133/119527) for a similar experiment. – Jonathon Reinhart Feb 05 '19 at 14:07
  • It's undefined behavior because, as you said yourself, it doesn't "exist" anymore. As a result, *anything* might happen; even getting the expected result. What probably happens is that it's just trying to read from the given (invalid) memory location anyway, and if it didn't do anything else with it, the original value might still be there. – Blaze Feb 05 '19 at 14:08
  • good write-up on what [undefined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) means – Sander De Dycker Feb 05 '19 at 14:12
  • 1
    I came across a similar bug in production code once, where the function returned the pointer. It "worked" for several years. It came to light when I put a `printf` statement after the function call (to trace an unrelated bug) which zapped the stack and the residual values. – cdarke Feb 05 '19 at 14:31
  • Undefined behavior is a lot like playing on the railroad tracks. You try it and everything is fine. One day, it isn't. – Tim Randall Feb 05 '19 at 15:21
  • Thank you all ,it is clear now. – user6497813 Feb 06 '19 at 09:28

1 Answers1

4

Dereferencing a pointer that points to an invalid object (e.g. to one with automatic storage duration that has gone out of scope) is undefined behaviour (cf, for example, this online C standard draft):

3.4.3

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).

So undefined behaviour means that anything might happen, even that it "works as intended" like in your case. Yet you must not rely on such a behaviour.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58