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!
As the memory allocated by malloc() is on the heap and not on the stack, you can access it regardless of which function you are in. If you want to pass around malloc()'ed memory, you have no other option than freeing it from the caller. (in reference counting terms, that's what is called an ownership transfer.)