返回函数前自由分配内存

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()的内存,你几乎没有别的选择.从呼叫者那里解放出来.(在参考计算术语中,这就是所谓的所有权转移.)


Jay*_*Jay 8

当然,如果你返回它,你可以释放在该函数之外的函数中分配的内存.

但是,另一种方法是修改你的函数,如下所示,调用者只分配和释放内存.这将与分配内存的函数的概念内联,负责释放内存.

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)


das*_*ght 5

是的,您可以释放在函数外部调用的函数中分配的内存; 这正是你在这种情况下需要做的.

替代方法包括将缓冲区及其长度传递给函数,并将实际长度返回给调用者fgets.这可能不是最佳选择,因为调用者需要在循环中调用您的函数.