JustKernel
Ray Of Hope
Return local pointer from function
Return local pointer from function. Is it safe.. It can’t be… You declare a pointer in the function, whose scope of life is only till the function lasts. So a pointer points a valid local variable, till the control is in the local function. As soon as the control is released from the function, the area allocated to the local variable is release and if you return address of this area (in the form of pointer), what actually you a returning………….. An address of area which is in possession of OS and which can be assigned to some other process of overwritten any time. Do you intended to do that….
int * foo()
{
int a = 10; //4 bytes of area allocated(suppose at address 0x1000) where 4 is stored.
int *p;
p = & a; // p = 0x1000 contain the address of area allocated to a.
return p; return 0x1000
}
void main()
{
int *q ;
q = foo();
printf(“%d”, *q)
//what is the value of q.. simple 0x1000. But what is the value of *q i.e what is value present at the address pointed by q. We don’nt know. The area that was allocated to ‘a’ in function foo has been freed. Now 0x1000 , though point to same area where ‘a’ was allocated, but the area is not in the stack of the main function and has been assigned to the global free pool. So this area is prone to being overwritten or assigned to some other process.
*q can print the correct value also like 10…. But is really prone to changed or junk value as now the program has no control over the area pointed by q.
}
Now the reason for the above anomaly is that, when the function foo is called the area is allocated for int (‘a’) from the local stack and is released as soon as the function exists (because a is an auto variable ).
Now to avoid this situation either declare a as static variable or declared it heap memory (by using malloc) so that its visibility is till the function ends.
<input id=”gwProxy” type=”hidden” /> <input id=”jsProxy” onclick=”jsCall();” type=”hidden” />
<input id=”gwProxy” type=”hidden” /><input id=”jsProxy” onclick=”jsCall();” type=”hidden” />
Anshul Makkar, anshul_makkar@justkernel.com
Originally Posted On: 2010-06-06 03:14:53
Leave a Reply