当你返回泄露的内存时修复内存泄漏?(fixing memory leaks when you're returning the leaked memory?)

编程入门 行业动态 更新时间:2024-10-26 23:28:56
当你返回泄露的内存时修复内存泄漏?(fixing memory leaks when you're returning the leaked memory?)

如何从漏洞本身返回的函数中修复内存泄漏?

例如,我创建一个char* returnMe = new char[24324]; returnMe最终从函数返回。 你如何解释这个内存泄漏? 一旦它被退回,你怎么摧毁它? 我有一些内存管理规则,在内存泄漏上抛出运行时错误来阻止它,所以我不能忽略它。

Orrr我是一个傻瓜,这不是泄漏,暗示泄漏在其他地方?

How do you fix a memory leak where you're returning from the function the leak itself?

For example, I make a char* returnMe = new char[24324]; returnMe is what ends up getting returned from the function. How do you account for this memory leak? How do you destroy it once it's been returned? I have some memory management rules in place that throw runtime errors on memory leaks to stop this, so I can't really ignore it.

Orrr am I a fool and this isn't a leak, implying that the leak is elsewhere?

最满意答案

如果你退回它并不是泄漏(好吧,这不是你的泄漏)。

您需要考虑资源所有权。 如果从函数返回已分配的缓冲区,则函数的调用者现在负责它。 API应该清楚地表明它需要在完成它时被释放。

无论是自己释放它还是将它传递给你的另一个函数来释放它(封装以防止需要完成而不仅仅是释放内存)是API的另一个问题。

It's not a leak if you return it (well, it's not your leak).

You need to think in terms of resource ownership. If you return an allocated buffer from your function, the caller of the function is now responsible for it. The API should make it clear that it needs to be freed when they're finished with it.

Whether they free it themselves or pass it to another of your functions to have it freed (encapsulation in case more needs to be done than just freeing the memory) is another issue for the API.

更多推荐

本文发布于:2023-08-06 22:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1457612.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存   当你   fixing   memory   returning

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!