Pergunta

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?

Foi útil?

Solução

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 from malloc in C - it can hide subtle errors. C is perfectly capable of converting the void * returned by malloc 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).

Outras dicas

Finally after understanding... I was able to get the concept.

  1. When we return the pointer p... definitely p, which was allocated on stack vanishes.

  2. Since values are returned with a call by value mechanism and p was holding an address of memory allocated on the heap. That address is still valid and holds reference to a valid memory location.

  3. Thus p itself vanishes, but the value returned by it is copied to a variable in the calling function and hence this justifies the correctness of the code.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top