Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free allocated memory before return a function

Tags:

People also ask

Can you free malloc after return?

If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free(). The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc(), or realloc().

Is memory automatically freed when a program exits?

Most memory on most OSes however will be automatically reclaimed when the process exits.

What happens in memory when a function is returned?

After the function returns, the stack memory of this function is deallocated, which means all local variables become invalid. The allocation and deallocation for stack memory is automatically done. The variables allocated on the stack are called stack variables, or automatic variables.


I am trying to return an array using malloc in a function:

char* queueBulkDequeue(queueADT queue, unsigned int size)
{
    unsigned int i;
    char* pElements=(char*)malloc(size * sizeof(char));
    for (i=0; i<size; i++)
    {
        *(pElements+i) = queueDequeue(queue);
    }
    return pElements;
}

The problem is that I need to free it because my MCU's heap size is limited. But I want to return it so I cannot free it in the function, right?. Can I free the allocated memory outside the function (where I call the function). Is there any best practices for this? Thank you in advance!