in Programming in C
1,371 views
2 votes
2 votes
void fun(int **pptr)
{
   int q = 10;
  *pptr = &q;
}

int main()
{
  int r = 20;
  int *p = &r;
  fun(&p);
  printf("%d", *p);
  return 0;
}

The output of the program is 10 . But as q here is an automatic variable, the result shouldn't be 10.

in Programming in C
by
1.4k views

4 Comments

that I know, chk my diagram once. and then tell me, where dangling pointer exists?
0
0
@2018

I am not getting , what fun2() actually doing here.

i is taking huge value, that could cause a stack overflow. But what do u mean by it?
0
0
functional call fun create temporary(local) mem for q in stack area, and life time of this mem is valid till execution of fun function call(or u can say you reserved that potion of mem to use it in fun function call only and after fun poped out from stack reservation no more valid for that portion of area any other function or program may use that portion again), after completion of this function fun activation record which was pushed at the time of function call now poped out and all reference to the local mem which was locally created in stack area are also destroyed, the purpose of fun2() AND bigger value of i is to use location of q which was previously used in fun(), each run of for loop create a block of mem and store 2oo, due to i<100000000000 it create lots of mem block and replaces each by 200, at some instances of time it uses portion of mem which was previously reserved for fun() function call(bcz we can use it, that block in fun no more reserved to particular function)
0
0

1 Answer

5 votes
5 votes
Best answer

@siddhartha You are absolutely right that it should print the garbage value. But it is printing 10. 

Here is the reason. This program is printing 10, because you are running this program in the windows environment. Windows does not clear the memory when the stack gets deleted. It just deletes the reference. What happens that you have the address in P, which is pointing to value 10, which has not been replaced by any other program, hence you are getting the 10. 

Run this program in Linux environment and i am 100% sure you will get 0 as output. In the Linux, when a stack gets deleted it reset all the memory as 0. Hence you get 0. 

Here, I run this program at the ideone.com which is a Linux based system. I get 0.

selected by
by

4 Comments

once carefully see code which i posted in comment surely u will get all ans to yr query
0
0
hmm ,understood. static u used for permanent change.

but auto may cause unexpected result
0
0
what is UB ?
0
0

Related questions