1 votes 1 votes void main() { int *x; x =f(); printf("%d", *x); } int *f() { int y = 7 ; return &y; } sumit goyal 1 asked Jan 18, 2018 • edited Jan 18, 2018 by sumit goyal 1 sumit goyal 1 428 views answer comment Share Follow See all 5 Comments See all 5 5 Comments reply Show 2 previous comments hs_yadav commented Jan 18, 2018 reply Follow Share it it he case of dagling pointer and here result of this execution would be compiler dependent ..... 0 votes 0 votes sumit goyal 1 commented Jan 18, 2018 reply Follow Share @hs_yadav Bro according to me it should be 7 , i have done many questions on pointer like this only plz explain detial 0 votes 0 votes MiNiPanda commented Jan 18, 2018 reply Follow Share You are trying to print the value of y. Here y is local to fun(). So after fun() call, fun() gets pushed onto the stack. Y gets some address there. Then after returning the address of y, the fun() pops out of the stack which means y also is no more present. Now the address that was allocated for y is lost. Which means x is pointing to some address which no more belongs to the given program. So when you try to access the value present in an address which is not part of your program, it gives error. 2 votes 2 votes Please log in or register to add a comment.
0 votes 0 votes yes, ans is unexpexted because when function definition is completed then local variable of function will discard abhicse answered Jan 18, 2018 abhicse comment Share Follow See 1 comment See all 1 1 comment reply sumit goyal 1 commented Jan 18, 2018 reply Follow Share Here you are not returning the value of y ..you are returning the address of y..so we can retain the value. 0 votes 0 votes Please log in or register to add a comment.