c - 如何使用 Clang 查找内存泄漏

标签 c memory-leaks clang clang-static-analyzer memory-leak-detector

我在我的机器 (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/

相关文章:

C- 在一维字节数组中索引 x、y、z 坐标

c - 链接时出现错误 "multiple definitions"的原因可能是什么?

android - 在没有任何静态引用的情况下使用上下文

ios - 如何调查 ios 中的内存泄漏?

c++ - gcc 可以编译可变参数模板而 clang 不能

c - 绕过C错误生成clang调试信息

c - 遍历数组似乎不起作用

c - 计算经过天数的公式

go - go GC 是否将整个对象保存在内存中,同时保留指向一个字段的内部指针?这会导致内存泄漏吗?

c++ - 在 C++ 中使用 decltype 声明指向方法的指针