简体   繁体   English

如何使用Clang查找内存泄漏

[英]How to find memory leaks with Clang

I have installed Clang in my machine (ubuntu) in order to find memory leaks in my C code. 我已经在我的机器(ubuntu)中安装了Clang,以便在我的C代码中查找内存泄漏。 I wrote a sample code in order to check the working of it which is as follows: 我编写了一个示例代码以检查其工作情况,如下所示:

/* 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;
}

I found some options in internet to compile like 我在互联网上找到了一些编译选项,例如

$ scan-build clang --analyze hello.c

and

$ scan-build clang -fsanitize=address hello.c

But none of them are showing any signs of memory leak. 但是它们都没有显示任何内存泄漏迹象。

scan-build: Using '/usr/bin/clang' for static analysis scan-build:使用“ / usr / bin / clang”进行静态分析
scan-build: Removing directory '/tmp/scan-build-2015-07-02-122717-16928-1' because it contains no reports. scan-build:删除目录“ / tmp / scan-build-2015-07-02-122717-16928-1”,因为其中不包含报告。
scan-build: No bugs found. scan-build:未发现错误。

Can anyone kindly tell how to correctly use Clang for Memory leak detection. 谁能告诉我如何正确使用Clang进行内存泄漏检测。

Interestingly, the clang static analyzer finds the memory leak if you declare void *x inside main : 有趣的是,如果在main内部声明void *x ,则clang静态分析器会发现内存泄漏:

int main() {
  void *x = malloc(2);
  x = 0; // Memory leak
  return 0;
}

Analyzing this code by running: 通过运行以下代码来分析此代码:

scan-build clang -g hello.c

gives a warning like: 给出如下警告:

hello.c:9:3: warning: Potential leak of memory pointed to by 'x'
  return 0;
  ^~~~~~~~

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

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