Suppose i define the following code:
int *func()
{
int *p=(int *)malloc(sizeof(int)); // memory is allocated from heap
// which can be accessed anytime.
return p; // but we created p which has a local scope and vanishes as
//soon as function exits.
}
Then how does this thing work? p being a local varible (a pointer holding a address to
the dynamic memory). I mean the memory itself from HEAP should definitely continue to exist, but the pointer variable has a local scope. How come i will be able to get this pointer?
pis simply a pointer which refers to the memory block that you’ve allocated.The lifetime of the allocated block extends beyond the end of the function.
It’s true that the actual pointer will go out of scope on return but you’ve already returned a copy of it it to the caller before then.
It would be better written as something like:
You’ll also notice the use of
voidin the function to explicitly state the function takes no parameters. That’s preferable to just having()which is subtly different (an indeterminate number of parameters).