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!
1) Yes, you can free() the malloc'ed memory outside the function
2) No, you cannot free it inside the function and have the data passed outside the function, so you must do 1) here
3) If you're concerned about scarce memory, you need to check for failure from memory allocations always, which you fail to do here, which is then likely to lead to a segfault