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?
p
is 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.
And, as an aside, you probably meant
int*
(in both cases) rather than*int
and(*int)
. In any event, you don't want to explicitly cast the return value frommalloc
in C - it can hide subtle errors. C is perfectly capable of converting thevoid *
returned bymalloc
into any suitable pointer type.
It would be better written as something like:
int *func (void) {
int *p = malloc (sizeof (int));
return p;
}
You'll also notice the use of void
in 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).