KiL*_*KiL 10 c malloc free pointers
我试图在函数中使用malloc返回一个数组:
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;
}
Run Code Online (Sandbox Code Playgroud)
问题是我需要释放它,因为我的MCU堆大小有限.但是我想退回它,所以我不能在功能中释放它,对吧?我可以在函数外部释放已分配的内存(我称之为函数).这有什么最佳做法吗?先感谢您!
tbe*_*ert 10
1)是的,你可以释放()函数外的malloc内存
2)不,你不能在函数内释放它并将数据传递到函数外部,所以你必须在这里做1)
3)如果你担心内存不足,你需要始终检查内存分配的失败,这是你在这里做不到的,这可能会导致段错误
小智 9
由于malloc()分配的内存在堆上而不在堆栈上,无论你使用哪个函数,都可以访问它.如果你想传递malloc()的内存,你几乎没有别的选择.从呼叫者那里解放出来.(在参考计算术语中,这就是所谓的所有权转移.)
当然,如果你返回它,你可以释放在该函数之外的函数中分配的内存.
但是,另一种方法是修改你的函数,如下所示,调用者只分配和释放内存.这将与分配内存的函数的概念内联,负责释放内存.
void queueBulkDequeue(queueADT queue, char *pElements, unsigned int size)
{
unsigned int i;
for (i=0; i<size; i++)
{
*(pElements+i) = queueDequeue(queue);
}
return;
}
Run Code Online (Sandbox Code Playgroud)
//在来电者中
char *pElements = malloc(size * sizeof(char));
queueBulkDequeue(queue, pElements, size);
//Use pElements
free(pElements);
Run Code Online (Sandbox Code Playgroud)