利用Valgrind进行内存泄露检查

Note: Valgrind is Linux only. If you aren't running Linux, or want a tool designed from the start to make debugging segfaults and memory issues easier, check out Cee Studio, a fully online C and C++ development environment from our sponsor. Cee Studio provides instant and informative feedback on memory issues.Valgrind is a multipurpose code profiling and memory debugging tool for Linux when on the x86 and, as of version 3, AMD64, architectures. It allows you to run your program in Valgrind's own environment that monitors memory usage such as calls to malloc and free (or new and delete in C++). If you use uninitialized memory, write off the end of an array, or forget to free a pointer, Valgrind can detect it. Since these are particularly common problems, this tutorial will focus mainly on using Valgrind to find these types of simple memory problems, though Valgrind is a tool that can do a lot more.

Alternatively, for Windows users who want to develop Windows-specific software, you might be interested in IBM's Purify, which has features similar to Valgrind for finding memory leaks and invalid memory accesses. A trial download is available.

Getting Valgrind

If you're running Linux and you don't have a copy already, you can get Valgrind from the Valgrind download page.

Installation should be as simple as decompressing and untarring using bzip2 (XYZ is the version number in the below examples)

bzip2 -d valgrind-XYZ.tar.bz2
tar -xf valgrind-XYZ.tar

which will create a directory called valgrind-XYZ; change into that directory and run

./configure
make
make install

Now that you have Valgrind installed, let's look at how to use it.

Finding Memory Leaks With Valgrind

Memory leaks are among the most difficult bugs to detect because they don't cause any outward problems until you've run out of memory and your call to malloc suddenly fails. In fact, when working with a language like C or C++ that doesn't have garbage collection, almost half your time might be spent handling correctly freeing memory. And even one mistake can be costly if your program runs for long enough and follows that branch of code.

When you run your code, you'll need to specify the tool you want to use; simply running valgrind will give you the current list. We'll focus mainly on the memcheck tool for this tutorial as running valgrind with the memcheck tool will allow us to check correct memory usage. With no other arguments, Valgrind presents a summary of calls to free and malloc: (Note that 18490 is the process id on my system; it will differ between runs.)

# valgrind --tool=memcheck program_name
=18515== malloc/free: in use at exit: 0 bytes in 0 blocks.
==18515== malloc/free: 1 allocs, 1 frees, 10 bytes allocated.
==18515== For a detailed leak analysis,  rerun with: --leak-check=yes

If you have a memory leak, then the number of allocs and the number of frees will differ (you can't use one free to release the memory belonging to more than one alloc). We'll come back to the error summary later, but for now, notice that some errors might be suppressed -- this is because some errors will be from standard library routines rather than your own code.

If the number of allocs differs from the number of frees, you'll want to rerun your program again with the leak-check option. This will show you all of the calls to malloc/new/etc that don't have a matching free.

For demonstration purposes, I'll use a really simple program that I'll compile to the executable called "example1"

#include <stdlib.h>
int main()
{
    char *x = malloc(100); /* or, in C++, "char *x = new char[100] */
    return 0;
}
valgrind --tool=memcheck --leak-check=yes example1

This will result in some information about the program showing up, culminating in a list of calls to malloc that did not have subsequent calls to free:

==2116== 100 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2116==    at 0x1B900DD0: malloc (vg_replace_malloc.c:131)
==2116==    by 0x804840F: main (in /home/cprogram/example1)

This doesn't tell us quite as much as we'd like, though -- we know that the memory leak was caused by a call to malloc in main, but we don't have the line number. The problem is that we didn't compile using the -g option of gcc, which adds debugging symbols. So if we recompile with debugging symbols, we get the following, more useful, output:

==2330== 100 bytes in 1 blocks are definitely lost in loss record 1 of 1
==2330==    at 0x1B900DD0: malloc (vg_replace_malloc.c:131)
==2330==    by 0x804840F: main (example1.c:5)

Now we know the exact line where the lost memory was allocated. Although it's still a question of tracking down exactly when you want to free that memory, at least you know where to start looking. And since for every call to malloc or new, you should have a plan for handling the memory, knowing where the memory is lost will help you figure out where to start looking.

There will be times when the --leak-check=yes option will not result in showing you all memory leaks. To find absolutely every unpaired call to free or new, you'll need to use the --show-reachable=yes option. Its output is almost exactly the same, but it will show more unfreed memory.

Finding Invalid Pointer Use With Valgrind

Valgrind can also find the use of invalid heap memory using the memcheck tool. For instance, if you allocate an array with malloc or new and then try to access a location past the end of the array:

char *x = malloc(10);
x[10] = 'a';

Valgrind will detect it. For instance, running the following program, example2, through Valgrind

#include <stdlib.h>

int main()
{
    char *x = malloc(10);
    x[10] = 'a';
    return 0;
}

with

valgrind --tool=memcheck --leak-check=yes example2

results in the following warning

==9814==  Invalid write of size 1
==9814==    at 0x804841E: main (example2.c:6)
==9814==  Address 0x1BA3607A is 0 bytes after a block of size 10 alloc'd
==9814==    at 0x1B900DD0: malloc (vg_replace_malloc.c:131)
==9814==    by 0x804840F: main (example2.c:5)

What this tell us is that we're using a pointer allocated room for 10 bytes, outside that range -- consequently, we have an 'Invalid write'. If we were to try to read from that memory, we'd be alerted to an 'Invalid read of size X', where X is the amount of memory we try to read. (For a char, it'll be one, and for an int, it would be either 2 or 4, depending on your system.) As usual, Valgrind prints the stack trace of function calls so that we know exactly where the error occurs.

Detecting The Use Of Uninitialized Variables

Another type of operation that Valgrind will detect is the use of an uninitialized value in a conditional statement. Although you should be in the habit of initializing all variables that you create, Valgrind will help find those cases where you don't. For instance, running the following code as example3

#include <stdio.h>

int main()
{
    int x;
    if(x == 0)
    {
        printf("X is zero"); /* replace with cout and include 
                                iostream for C++ */
    }
    return 0;
}

through Valgrind will result in

==17943== Conditional jump or move depends on uninitialised value(s)
==17943==    at 0x804840A: main (example3.c:6)

Valgrind is even smart enough to know that if a variable is assigned the value of an uninitialized variable, that that variable is still in an "uninitialized" state. For instance, running the following code:

#include <stdio.h>

int foo(int x)
{
    if(x < 10)
    {
        printf("x is less than 10\n");
    }
}

int main()
{
    int y;
    foo(y);
}

in Valgrind as example4 results in the following warning:

==4827== Conditional jump or move depends on uninitialised value(s)
==4827==    at 0x8048366: foo (example4.c:5)
==4827==    by 0x8048394: main (example4.c:14)

You might think that the problem was in foo, and that the rest of the call stack probably isn't that important. But since main passes in an uninitialized value to foo (we never assign a value to y), it turns out that that's where we have to start looking and trace back the path of variable assignments until we find a variable that wasn't initialized.

This will only help you if you actually test that branch of code, and in particular, that conditional statement. Make sure to cover all execution paths during testing!

What else will Valgrind Find

Valgrind will detect a few other improper uses of memory: if you call free twice on the same pointer value, Valgrind will detect this for you; you'll get an error:

Invalid free()

along with the corresponding stack trace.

Valgrind also detects improperly chosen methods of freeing memory. For instance, in C++ there are three basic options for freeing dynamic memory: free, delete, and delete[]. The free function should only be matched with a call to malloc rather than a call to, say, delete -- on some systems, you might be able to get away with not doing this, but it's not very portable. Moreover, the delete keyword should only be paired with the new keyword (for allocation of single objects), and the delete[] keyword should only be paired with the new[] keyword (for allocation of arrays). (Though some compilers will allow you to get away with using the wrong version of delete, there's no guarantee that all of them will. It's just not part of the standard.)

If you do trigger one of these problems, you'll get this error:

 Mismatched free() / delete / delete []

which really should be fixed even if your code happens to be working.

What Won't Valgrind Find?

Valgrind doesn't perform bounds checking on static arrays (allocated on the stack). So if you declare an array inside your function:

int main()
{
    char x[10];
    x[11] = 'a';
}

then Valgrind won't alert you! One possible solution for testing purposes is simply to change your static arrays into dynamically allocated memory taken from the heap, where you will get bounds-checking, though this could be a mess of unfreed memory.

A Few More Caveats

What's the drawback of using Valgrind? It's going to consume more memory -- up to twice as much as your program normally does. If you're testing an absolutely huge memory hog, you might have issues. It's also going to take longer to run your code when you're using Valgrind to test it. This shouldn't be a problem most of the time, and it only affects you during testing. But if you're running an already slow program, this might affect you.

Finally, Valgrind isn't going to detect every error you have -- if you don't test for buffer overflows by using long input strings, Valgrind won't tell you that your code is capable of writing over memory that it shouldn't be touching. Valgrind, like another other tool, needs to be used intelligently as a way of illuminating problems.

Summary

Valgrind is a tool for the x86 and AMD64 architectures and currently runs under Linux. Valgrind allows the programmer to run the executable inside its own environment in which it checks for unpaired calls to malloc and other uses of invalid memory (such as ininitialized memory) or invalid memory operations (such as freeing a block of memory twice or calling the wrong deallocator function). Valgrind does not check use of statically allocated arrays.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容