在程序结束时释放malloc的良好实践? [英] Good practice to free malloc's at program conclusion?

查看:88
本文介绍了在程序结束时释放malloc的良好实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的程序,该程序读取动态分配的内存(malloc)中的一堆ini文件设置,然后在循环中执行很长时间,然后结束.当我运行valgrind时,我看到为ini字符串分配的内存没有释放.

I have a simple program which reads a bunch of ini file settings in memory allocated dynamically (malloc), then does stuff in loops for a long time, then ends. When I run valgrind I see that the memory I malloc'ed for my ini strings is not freed.

一方面,我认为这没关系,因为程序正在关闭(循环中没有内存泄漏).

On the one hand, I think that it shouldn't matter since the program is shutting down (and no memory is leaked in the loops).

另一方面,我喜欢valgrind帮我大拍一下清理自己的烂摊子.除了背面的拍子以外...是否在终止时释放每个分配的空间(或者只是让操作系统清理)是一种好习惯?如果是的话,如何跟踪我的哪个指针指向了malloc的内存(相对于默认的字符串常量),以确保释放正确的东西?

On the other hand, I like when valgrind gives me a big pat on the back for cleaning up my own mess. Aside from the pat on the back...is it good practice to release every malloc'ed space upon termination (or just let the OS cleanup)? If it is, how can I track which of my pointers point to malloc'ed memory (versus pointing to string constants which are the defaults) to ensure I'm releasing the right stuff?

推荐答案

在关闭时释放malloc的主要优点是帮助valgrind跟踪内存泄漏-当您的页面充满错误时,您将找不到真正的内存泄漏毕竟是肯定的.除此之外,清理操作系统也没有什么害处.

The main advantage to freeing mallocs at shutdown is to help valgrind track down your memory leaks - you can't find true memory leaks when you have pages full of false positives, after all. Apart from that, though, there's no harm in letting the OS clean up.

关于跟踪字符串常量与堆分配值的比较,一种简单的策略是始终使用堆值-在启动时用strdup() d字符串填充默认值.

As for keeping track of string constants vs heap allocated values, one simple policy would be to always use heap values - fill in the defaults with strdup()d strings at startup.

这篇关于在程序结束时释放malloc的良好实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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