若使用Memcheck,命令如下:
valgrind --leak-check=yes myprog arg1 arg2
Memcheck是Valgrind的缺省工具。--leak-check选项将打开内存泄漏的详细检测器。
如果说你的内存泄漏错误代码,即myprog如下所示:
#include <stdlib.h>
void f(void)
{
int* x = malloc(10 * sizeof(int));
x[10] = 0; // problem 1: heap block overrun
} // problem 2: memory leak -- x not freed
int main(void)
{
f();
return 0;
}
运行过程中,问题1的错误指示消息将会显示出来,主要是内存越界
==19182== Invalid write of size 4
==19182== at 0x804838F: f (example.c:6)
==19182== by 0x80483AB: main (example.c:11)
==19182== Address 0x1BA45050 is 0 bytes after a block of size 40 alloc'd
==19182== at 0x1B8FF5CD: malloc (vg_replace_malloc.c:130)
==19182== by 0x8048385: f (example.c:5)
==19182== by 0x80483AB: main (example.c:11)
对于问题2,内存泄漏的消息如下所示:
==19182== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==19182== at 0x1B8FF5CD: malloc (vg_replace_malloc.c:130)
==19182== by 0x8048385: f (a.c:5)
==19182== by 0x80483AB: main (a.c:11)
检查core down
ulimit -c unlimited