我在我的机器 (ubuntu) 中安装了 Clang,以便在我的 C 代码中查找内存泄漏。我写了一个示例代码来检查它的工作情况,如下所示:
/* File: hello.c for leak detection */
#include <stdio.h>
#include <stdlib.h>
void *x;
int main() {
x = malloc(2);
x = 0; // Memory leak
return 0;
}
我在网上找到了一些编译选项
$ scan-build clang --analyze hello.c
和
$ scan-build clang -fsanitize=address hello.c
但是它们都没有显示出任何内存泄漏的迹象。
scan-build: Using '/usr/bin/clang' for static analysis
scan-build: Removing directory '/tmp/scan-build-2015-07-02-122717-16928-1' because it contains no reports.
scan-build: No bugs found.
谁能告诉我如何正确使用 Clang 进行内存泄漏检测。
最佳答案
有趣的是,如果您在 main
中声明 void *x
,clang 静态分析器会发现内存泄漏:
int main() {
void *x = malloc(2);
x = 0; // Memory leak
return 0;
}
通过运行分析此代码:
scan-build clang -g hello.c
发出如下警告:
hello.c:9:3: warning: Potential leak of memory pointed to by 'x'
return 0;
^~~~~~~~
关于c - 如何使用 Clang 查找内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31177633/