如何使用Clang查找内存泄漏 [英] How to find memory leaks with Clang

查看:102
本文介绍了如何使用Clang查找内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在计算机(ubuntu)中安装了Clang,以便在我的C代码中查找内存泄漏.我编写了一个示例代码来检查其工作情况,如下所示:

I have installed Clang in my machine (ubuntu) in order to find memory leaks in my C code. 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

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

但是它们都没有显示任何内存泄漏迹象.

But none of them are showing any signs of memory leak.

scan-build:使用'/usr/bin/clang'进行静态分析
scan-build:删除目录"/tmp/scan-build-2015-07-02-122717-16928-1",因为它不包含任何报告.
扫描构建:未发现错误.

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进行内存泄漏检测.

Can anyone kindly tell how to correctly use Clang for Memory leak detection.

推荐答案

有趣的是,如果在 main 内声明 void * x ,则clang静态分析器会发现内存泄漏:

Interestingly, the clang static analyzer finds the memory leak if you declare void *x inside main:

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

通过运行以下代码来分析此代码:

Analyzing this code by running:

scan-build clang -g hello.c

发出如下警告:

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

这篇关于如何使用Clang查找内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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