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().
Most memory on most OSes however will be automatically reclaimed when the process exits.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With