Search code examples
cpointersdynamic-memory-allocation

Is memory allocated with malloc or calloc deallocated at the end of a function?


I pass a pointer of a given type to a function. In the function I allocate the memory needed:

Pointer = (mytype * ) malloc (N* sizeof (mytype));

And it all goes well. After the function ends another one calls pointer.

But the previously filled pointer is now without memory.

Shouldn't pointer have kept its filled memory?

Or does the ending of a function deallocate the memory?

Sorry but I am unable to paste my code because I work on a non connected PC.


Solution

  • No, but you're not returning the pointer to the caller. The argument inside the function is not the same as the value at the calling site, so changing it by assigning the return value from malloc() doesn't change the caller's value.

    This:

    Foo *foo;
    
    AllocateAFoo(foo);
    

    has no chance of changing the value of foo after the function returns, even if the argument is assigned to inside the function. This is why malloc() returns the new value.

    You need to do that also:

    mytype * Allocate(size_t num)
    {
      return malloc(num * sizeof (mytype));
    }
    

    This means that there's no point in sending the uninitialized pointer from the caller to the function, so don't.

    Also, you shouldn't cast the return value of malloc() in C.

    Also, you need to be aware that malloc() is just a function like any other. How would you write a function that reacts when execution leaves other functions? The answer is of course "you can't", and thus malloc() can't either.