Click here to Skip to main content
15,887,464 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
main()
int *p;
int*fun();
n
p=fun();

printf("%d",*p);

}


int *fun()
 {
  int d=20;
  return (&d);
}



In the above function ,when fun() return ,the p pointer contains the address of d variable . But, the printf() statement fails as when fun() returns the d is destroyed because of the scope rule . My question is that ,when we call by reference through main then we can access the values . in this case ,why the scope rules fails .
Posted
Updated 24-Nov-11 7:04am
v2

Nothing fails, apart from your code. The variable d is a local variable in function fun() which means that it does not exist outside of that function. So when fun() returns its address it is returning an address that will no longer exist, which is why the printf() fails. If fun() returned the value of d then your code could print it out in main().
 
Share this answer
 
Comments
BrainlessLabs.com 24-Nov-11 13:47pm    
I agree with Richard.
Sergey Alexandrovich Kryukov 24-Nov-11 15:54pm    
Good explanation, a 5.
--SA
Mohibur Rashid 25-Nov-11 2:39am    
Agreed
"scope", as in the language rules for symbol "visibility" has nothing to do with this.

"Data/Object Lifetime" is what this is all about. You have fallen into the most basic trap, you pointed to a data item (d) whose lifetime is shorter than the thing that points to it.

Nobody would be surprised if you crashed after continuing to use a pointer to an object or structure that you then called "free()" or "delete" on. Of course the pointer is to something that has disappeared / available for reuse. Yet it is possible to do the same thing with pointers to "local" (i.e. stack based) objects / variables.

This is just one way to accomplish this, if indeed it can be considered an accompishment. Creating a thread while passing the address of a local variable to it as one of the arguments is another. This should be one of those "red flags" that programmers need to commit to memory.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 24-Nov-11 15:55pm    
My 5.
--SA
enhzflep 24-Nov-11 19:03pm    
Mine too. :thumbsup:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900