简体   繁体   English

不使用free()malloc的警告

[英]warning for not using free() malloc

Are there any safeguards built into GCC that check for memory leaks? GCC内置了哪些安全措施来检查内存泄漏? If so how can I use them? 如果是这样,我该如何使用它们? When I compile with "gcc -Wall -o run run.c", the compiler does not seem to care if any allocated heap-space is being freed at the end of the code. 当我使用“gcc -Wall -o run run.c”进行编译时,编译器似乎并不关心在代码末尾是否释放了任何已分配的堆空间。 I could not find any simple fixes for this on Google. 我在Google上找不到任何简单的修复方法。

Thanks much for your time. 非常感谢你的时间。

EDIT: Google Searches did point to Valgrind among other tools. 编辑:谷歌搜索确实指向Valgrind和其他工具。 But I was curious as to why the compiler cant deal with this issue. 但我很好奇为什么编译器无法解决这个问题。 As a newbie, it seemed a simple enough task to check if every "malloc" has a "free" associated with it. 作为一个新手,检查每个“malloc”是否具有与之关联的“免费”似乎是一项非常简单的任务。

There are two ways to analyze code for problems - static analysis and run-time analysis. 有两种方法可以分析问题的代码 - 静态分析和运行时分析。 Static analysis reads the code - this is what compilers do really well. 静态分析读取代码 - 这是编译器真正做得很好的。 Run-time analysis for code problems happens when the code is linked against another set of libraries that see what the code actually does as it runs under surveillance. 代码问题的运行时分析发生在代码链接到另一组库时,这些库可以看到代码在监视下运行时实际执行的操作。 Finding memory leaks is difficult for static analysis but not for a run-time analysis package. 查找内存泄漏对于静态分析很困难,但对于运行时分析包则不然。

Other run-time analyses are things like code coverage - does all parts of your code run? 其他运行时分析就像代码覆盖一样 - 代码的所有部分都运行了吗? gcov does this, like valgrind and electric fence look for memory problems like leaks. gcov这样做,就像valgrind和电栅栏一样寻找泄漏等记忆问题。

So, no, there are no really good compiler safeguards for testing memory leaks. 所以,不,没有真正好的编译器保护措施来测试内存泄漏。

There is -fsanitize=leak GCC flag. -fsanitize=leak GCC标志。

It overrides malloc / calloc / free to make them count allocated and freed blocks of memory. 它会覆盖malloc / calloc / free以使它们计数分配并释放内存块。
If your program is compiled with this flag, it prints information about detected leaks to the terminal after execution. 如果使用此标志编译程序,则会在执行后将有关检测到的泄漏的信息打印到终端。

You can read about it here and here . 你可以在这里这里阅读它。


Also, I have never used it, so this answer is completely based on GCC manual. 此外,我从未使用它,所以这个答案完全基于GCC手册。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM