1
votes

I have a function where malloc is used to allocated a pointer and the pointer is passed to another function and thats passed to another function, where its used last.

My question is, can I call free in the final function for that allocated pointer? Or I need to call in the function where malloc is called.

Issue faced is , we see a memory leak since free for this allocated pointer is not coded till date. So my job is to fix the memory leak right now.

3

3 Answers

1
votes

Strictly speaking you can free it anywhere, as long as you free it exactly once and after last use. The $1MM question is how you enforce this easily, in light of future use? Passing in pointers with ownership transfer semantics is in general bad. Returning pointers with allocation transfer is also bad, in general. If you design an API, consider abstracting the object being allocated and have allocate/free functions (eg. allocate_widget and free-widget). The API use should not know that the widget is allocated with malloc() and must be freed with free().

1
votes

You can do either, but not both. It is usually better for design to free memory in the same function where you allocate it.

0
votes

You can call free in the final function for that allocated pointer, but it's not a good practice. Good practice is to call free function inside the function that owns the main pointer to the allocated memory (that may not be the function that allocates memory). Here's an example:

void func() 
{
    void* ptr = malloc(...); // ptr variable declared and initialized here.
    func2(ptr);
    func3(ptr);
    func4(ptr);
    free(ptr); // Free memory in function where ptr is declared.
}

Or, if malloc and free are incapsulated in higher-level functions:

void func() 
{
    void* ptr = allocateObject(...); // This function calls "malloc".
    func2(ptr);
    func3(ptr);
    func4(ptr);
    freeObject(ptr); // This function calls "free".
}

Consider also that C free function free dynamic allocated memory but don't change ptr variable value. So if you're experiencing memory leaks a good practice is to set pointer variables to NULL after calling free. This way debugging the code you may immediately know if memory is allocated (ptr != NULL) or no (ptr == NULL)

if(ptr != NULL) 
{
    free(ptr);
    ptr = NULL;
}