a urget help from someone!!!!!!!

vignesh1988i's Avatar
Banned
int * fun();
void main()
{
int *l;
clrscr();
l=fun();
printf("hi : ");
printf("%d",*l);
getch();
}
int *fun()
{
int j=90;
return &j;
}

pll.... say the output for this with a proper justifications !!!!!!!!!
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
What is your expectation of the output and did you try running it ?
0
vignesh1988i's Avatar
Banned
YA of course.... sir it's printing some garbage value... i know it will print garbage value... but I need to know the reason why it's printing so....

And if i don't place that printf() statement , the value is correctly printing as 90...... so.. plz.. state me the reason .... sir... thank u
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
You have to understand the memory mapping for that. I would try to explain. You are returning address of a variable which is out of scope which means you are returning memory address which can be allocated later and now when you call the printf with hi as parameter the returned memory is being filled by some value
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Yep, the output is undefined because j is local to fun() and its address is no longer valid when the function returns.

So if the program needs to return the address of a new integer then you should create a new one on the heap with new or malloc, and remember somewhere in the program to delete/free it when you've finished with it, otherwise you get a memory leak.
0
vignesh1988i's Avatar
Banned
sir , how can it be invalid when the address returns to the main() function....... the main problem is the printf() statement , if i give that it's printing statement inbetween these it's printing some garbage value ,.... if i directly print as *j , the value is correcly printing....

for shabbir sir .. sir kindly explain me in detail ,how the memory mapping is done >...
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
OK, the address itself isn't invalid, what is invalid is the assumption that j still exists. C and C++ pass arguments to functions by placing them on the stack, and local (automatic) variables are also created on the stack. So what your program does is to call fun() with no parameters; fun() creates j on the stack, then when it returns its stack frame and everything in it is discarded (although not necessarily changed). The main function then calls printf with a parameter "hi" which overwrites the memory that j previously occupied. Then you call printf a second time with two parameters which overwrite the memory that j previously occupied for the second time.

So that is why the program displays garbage for j. It's because you are assuming that j still exists, and that assumption is wrong. The problem is NOT the printf statement - both of those are perfectly fine.