免费分配的内存之前返还功能 [英] Free allocated memory before return a function

查看:120
本文介绍了免费分配的内存之前返还功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用返回数组的的malloc 的一个函数:

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;
}

问题是我需要的免费的,因为我的MCU的堆大小是有限的。但是,我想退货,所以我不能释放它的功能吧?我可以释放分配的内存功能外(在那里我调用函数)。对此有任何的最佳做法?谢谢你在前进!

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!

推荐答案

作为由malloc(分配的内存)在堆上,而不是在栈中,你可以不管哪个功能,您在访问它。如果你想通过各地的malloc()'编的内存,你必须比字面上从主叫释放它没有其他选择。 (在引用计数而言,这就是被称为过户。)

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

这篇关于免费分配的内存之前返还功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆