使用 Valgrind 时遇到的最常见错误
Valgrind 以 (file.c:line_no)
格式为你提供错误发生在每行末尾的行。valgrind 中的错误按以下方式汇总:
ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
最常见的错误包括:
- 非法的读/写错误
==8451== Invalid read of size 2
==8451== at 0x4E7381D: getenv (getenv.c:84)
==8451== by 0x4EB1559: __libc_message (libc_fatal.c:80)
==8451== by 0x4F5256B: __fortify_fail (fortify_fail.c:37)
==8451== by 0x4F5250F: __stack_chk_fail (stack_chk_fail.c:28)
==8451== by 0x40059C: main (valg.c:10)
==8451== Address 0x700000007 is not stack'd, malloc'd or (recently) free'd
当代码开始访问不属于程序的内存时会发生这种情况。访问的内存大小还可以指示使用的变量。
- 使用未初始化的变量
==8795== 1 errors in context 5 of 8:
==8795== Conditional jump or move depends on uninitialised value(s)
==8795== at 0x4E881AF: vfprintf (vfprintf.c:1631)
==8795== by 0x4E8F898: printf (printf.c:33)
==8795== by 0x400548: main (valg.c:7)
根据错误,在 valg.c
的 main
的第 7 行,对 printf()
的调用将未初始化的变量传递给 printf
。
- 非法释放内存
==8954== Invalid free() / delete / delete[] / realloc()
==8954== at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8954== by 0x4005A8: main (valg.c:10)
==8954== Address 0x5203040 is 0 bytes inside a block of size 240 free'd
==8954== at 0x4C2EDEB: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8954== by 0x40059C: main (valg.c:9)
==8954== Block was alloc'd at
==8954== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==8954== by 0x40058C: main (valg.c:7)
根据 valgrind 的说法,代码在 valg.c
的第 10 行非法地(第二次)释放了内存,而它已经在第 9 行释放了,并且块本身在第 7 行被分配了内存。