使用 Valgrind 時遇到的最常見錯誤

Valgrind 以 (file.c:line_no) 格式為你提供錯誤發生在每行末尾的行。valgrind 中的錯誤按以下方式彙總:

ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

最常見的錯誤包括:

  1. 非法的讀/寫錯誤
==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

當程式碼開始訪問不屬於程式的記憶體時會發生這種情況。訪問的記憶體大小還可以指示使用的變數。

  1. 使用未初始化的變數
==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.cmain 的第 7 行,對 printf() 的呼叫將未初始化的變數傳遞給 printf

  1. 非法釋放記憶體
==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 行被分配了記憶體。