释放呼叫者或被呼叫者中的内存? [英] Freeing memory in caller or callee?

查看:110
本文介绍了释放呼叫者或被呼叫者中的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个函数(说"fun()")分配内存,并将指针返回到分配的内存. 我应该如何确保释放该内存.由于返回给调用者,我无法立即在函数"fun()"中释放它. 如果fun()是库的一部分怎么办?释放内存是谁的责任. 如果是fopen(),则由fclose()释放内存.但是在我的情况下,"fun()"被反复调用.因此,我迫不及待地想释放内存.

A function (Say "fun()") allocates memory and returns the pointer to allocated memory. How should I make sure I that this memory is released. I can't release it immediately in function "fun()" as it is returned to caller. And what if fun() is part of library? Whose responsibility it is to free memory. In case of fopen(), the memory is released by fclose(). But in my case, "fun()" is called repeatedly. So I can not wait till end to release the memory.

推荐答案

以下是C的答案,在OP承认使用C ++之前发布.使用该语言,请使用RAII和智能指针,如其他人所推荐.

The following is the answer for C, posted before the OP confessed to using C++. In that language, use RAII and smart pointers, as recommended by others.

如果函数返回分配的内存,则调用者负责释放,这必须在函数的文档中说明.

If a function returns allocated memory, then the caller is responsible for deallocation and this must be stated in the function's documentation.

如果需要更多清理,则由free提供,或者在将来的库版本中可能需要这种清理,那么您应该提供清理功能(例如stdiofclose一起使用)释放.如果您无法预测将来是否需要进行额外的清理,那么最好在某个时候进行清理.包装free很便宜.

If more cleanup is needed then is offered by free, or such cleanup may to be needed in future versions of the library, then you should offer a cleanup function (like stdio does with fclose) that does the deallocation. If you can't predict whether extra cleanup may be necessary in the future, then it's a good idea to assume it will be at some point. Wrapping free is cheap.

将其视为一种对称形式:如果客户端从库中获取资源(对象),则最终由客户负责将其交还给库进行处置:

Think of it as a form of symmetry: if the client gets a resource (object) from the library, then it is eventually responsible for handing it back to the library for disposal:

void use_the_foo_library()
{
    Foo *f = make_foo();
    if (f == NULL)
        ERROR();

    foo_do_bar(f);
    foo_do_baz(f);

    foo_destroy(f);
}

在foolib 1.0中,foo_destroy只是

where in foolib 1.0, foo_destroy is just

void foo_destroy(Foo *p)
{
    free(p);
}

但是在2.0版中,它可能已经发展到

but in version 2.0, it may have grown to

void foo_destroy(Foo *p)
{
    fclose(p->logfile);
    free(p);
}

等此样式与不透明指针设计模式一致.它还使您可以随时用专用内存分配器(例如

etc. This style is consistent with the opaque pointer design pattern. It also gives you the freedom of replacing malloc and free at any point with a special purpose memory allocator, such as a pool allocator, without having to change any client code.

这篇关于释放呼叫者或被呼叫者中的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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