bing@ubuntu:~/work$ valgrind --leak-check=full ./mem_file
==10566== Memcheck, a memory error detector
==10566== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==10566== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==10566== Command: ./mem_file
==10566==
==10566== Invalid write of size 4
==10566== at 0x400544: f (mem_file.c:6)
==10566== by 0x400555: main (mem_file.c:12)
==10566== Address 0x5204068 is 0 bytes after a block of size 40 alloc'd
==10566== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10566== by 0x400537: f (mem_file.c:5)
==10566== by 0x400555: main (mem_file.c:12)
==10566==
==10566==
==10566== HEAP SUMMARY:
==10566== in use at exit: 40 bytes in 1 blocks
==10566== total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==10566==
==10566== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==10566== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10566== by 0x400537: f (mem_file.c:5)
==10566== by 0x400555: main (mem_file.c:12)
==10566==
==10566== LEAK SUMMARY:
==10566== definitely lost: 40 bytes in 1 blocks
==10566== indirectly lost: 0 bytes in 0 blocks
==10566== possibly lost: 0 bytes in 0 blocks
==10566== still reachable: 0 bytes in 0 blocks
==10566== suppressed: 0 bytes in 0 blocks
==10566==
==10566== For counts of detected and suppressed errors, rerun with: -v
==10566== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
==10566== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==10566== by 0x400537: f (mem_file.c:5)
==10566== by 0x400555: main (mem_file.c:12)
Memcheck对未初始化变量,同样会有错误提示,通常提示信息为Conditional jump or move depends on uninitialised value(s)。这类错误的roo cause比较难发现,使用--track-origins=yes来获取更多信息。
该选项虽会使Memcheck运行更慢但额外信息会使开发者更容易的找到未初始化变量的位置。
Valgrind 内存错误类型
Illegal read/Illegal write errors
Use of Uninitialised values
Use of uninitialised or unaddressable values in system calls
Illegal frees
When a heap block is freed with an inappropriate deallocation function