我如何使用valgrind来查找内存泄漏?

如何使用valgrind查找程序中的内存泄漏?

请有人帮助我,描述执行程序的步骤?

我使用Ubuntu 10.04,我有一个程序ac ,请帮助我。

尝试这个:

valgrind --leak-check=full -v ./your_program

只要安装了valgrind,它会通过你的程序,告诉你什么是错的。 它可以给你指针和大概的地方,你的泄漏可能被发现。 如果你是segfault,试着通过gdb运行。

你可以运行:

 valgrind --leak-check=full --log-file="logfile.out" -v [your_program(and its arguments)] 

我想通过提供关于如何有效使用Valgrind以及如何解决内存泄漏的更详细的解释来构buildRageD的伟大答案。

不要侮辱操作系统,但是对于那些对Linux来说还是个新手的人,你可能需要在你的系统上安装Valgrind。

 sudo apt-get install valgrind #mainly Ubuntu sudo yum install valgrind #RHEL, CentOS, Fedora, etc. 

Valgrind很容易用于C / C ++代码,但如果configuration正确,甚至可以用于其他语言(请参阅Python for Python)。

为了很好的诊断你的C / C ++程序的内存泄漏,把可执行文件传给Valgrind。

 valgrind --leak-check=full ./driver 

这将在执行你的程序结束时产生一个报告(希望)如下所示:

 HEAP SUMMARY: in use at exit: 0 bytes in 0 blocks total heap usage: 6 allocs, 6 frees, 104,200 bytes allocated All heap blocks were freed -- no leaks are possible 

但是,现在假设我们发现了内存泄漏。 你如何解决它们? 假设错误报告如下所示:

 HEAP SUMMARY: in use at exit: 13 bytes in 1 blocks total heap usage: 1 allocs, 0 frees, 13 bytes allocated 13 bytes in 1 blocks are definitely lost in loss record 1 of 1 at 0x4C28BE3: malloc (vg_replace_malloc.c:299) by 0x400885: main (in /home/peri461/path/to/driver) LEAK SUMMARY: definitely lost: 13 bytes in 1 blocks indirectly lost: 0 bytes in 0 blocks possibly lost: 0 bytes in 0 blocks still reachable: 0 bytes in 0 blocks suppressed: 0 bytes in 0 blocks 

那么,有13个字节丢失。 它怎么发生的? 错误报告只是说“主”。 这是因为可执行文件是如何编译的。 我们实际上可以逐行获得详细的错误信息。 重新编译您的程序,并提供关于debugging源代码的信息:

 gcc -o driver -std=c11 -Wall file1.c file2.c #suppose it was this at first gcc -o driver -std=c11 -Wall -ggdb3 file1.c file2.c #add -ggdb3 to it 

然后再运行Valgrind,你很好。 你应该能够找出现在造成内存泄漏的原因。


另外,RageD提到的是-v标志。

 -v, --verbose Be more verbose. Gives extra information on various aspects of your program, such as: the shared objects loaded, the suppressions used, the progress of the instrumentation and execution engines, and warnings about unusual behaviour. Repeating the option increases the verbosity level. 

最后,这里有一些更多的select – --leak-check标志。

 --leak-check=<no|summary|yes|full> [default: summary] When enabled, search for memory leaks when the client program finishes. If set to summary, it says how many leaks occurred. If set to full or yes, each individual leak will be shown in detail and/or counted as an error, as specified by the options --show-leak-kinds and --errors-for-leak-kinds.