-1

Why is the First Printing Statement in main(), printing 11 ?

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

int main(){
    int i = 10;
    int *p = &i;
    foo(&p);    
    printf("%d ", *p);          //Printing 11
    printf("%d ", *p);          //Printing Random value
    return 0;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294

1 Answers1

6

Inside foo() , you're assigning the address of a automatic local variable j to *p. After foo() has finished execution, j does not exist anymore and thus, using (derererencing) p furthermore in main() invokes undefined behavior.

Now, the output of UB is, well, undefined.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • I agree with your answer, but the thing is, why the first Printf() in main() is printing the correct value i.e. 11 ? – Arvind Rajput Jun 15 '15 at 20:35
  • @ArvindRajput it _seems_ to print the _correct_ value, however there is no gurantee that it **will** print always. That's the _beauty_ of UB. :-) – Sourav Ghosh Jun 15 '15 at 20:37
  • 1
    @ArvindRajput: The value is probably left on the stack intact for the first call to `printf`, but then the actual `printf` call overwrites it. You can't count on that behavior, though. – Fred Larson Jun 15 '15 at 20:45