0
#include <stdio.h>
void foo(int **p)
{
 int j=2;
 *p=&j;
 printf("%d  \n",**p );

}
int main()
{
 int i=97 ;
 int *p=&i;
 foo(&p);
 printf("%d \n",*p );
 return 0;
}

According to definition :A local variable is destroyed at the moment that the program execution reaches the end of the method in which the local variable is defined Then how in main() func it is still able to print 2. If int j=2; is already destroyed? Is it like the variables gets destroyed but it is still accessible by addresses?I know this is call by reference

  • You have passed the address of `p` as a parameter to `foo`. In foo, the pointer is set to the address of `j` and the value (2)` is printed before return. Now back in `main()` the fun begins. There `p` is a *Dangling-Pointer* because the address it holds is to an object that no longer exists. Attempts to access values at that address results in *Undefined Behavior* (your code could continue to appear to work, or SegFault, or anything in between) – David C. Rankin May 20 '21 at 10:25
  • Variables aren't "destroyed". In order to understand this fully, you must simply realize that computer programs either keep track of the contents of a RAM cell or they don't. In case they don't, they just let whatever value that happened to be in the cell be - it no longer cares about the memory cell. The linked duplicate has a nice analogy for it all. – Lundin May 20 '21 at 10:27
  • Additionally, see [What is undefined behavior and how does it work?](https://software.codidact.com/posts/277486) where I picked this very scenario as one of the examples. – Lundin May 20 '21 at 10:28
  • @DavidC.Rankin Thanks a lot. Got it now. – enthusiasticcoder May 20 '21 at 11:02
  • @Lundin Yep checked out that link thanks for the response. – enthusiasticcoder May 20 '21 at 11:03
  • @Lundin: Note that the duplicate you linked to is C++, not C. However, it is such a good analogy that I think that it was still worth linking to it. The only thing a C programmer must know to understand the question is that `std::cout` is equivalent to `printf`. – Andreas Wenzel May 21 '21 at 21:14
  • @AndreasWenzel We use that one as canonical dupe for this C FAQ question too. It's better than to dig up some other random question. – Lundin May 24 '21 at 07:54

0 Answers0