mtraceを使ってmemory leakを検出しfree忘れを見つける
Ulrich DrepperによってGNU C Libraryで実装されている。
buf2をfreeし忘れている
#include <stdio.h>
#include <malloc.h>
#include <mcheck.h> /* for check memory leak */
int
main()
{
char *buf1, *buf2;
mtrace();
buf1 = (char*)malloc(10);
buf2 = (char*)malloc(10);
free(buf1); /* free only buf1 */
muntrace();
return(0);
}
$ gcc -o free free.c -g $ env MALLOC_TRACE=./free.dat ./free # MALLOC_TRACEでtrace結果を保存するfileを指定 $ mtrace free free.dat # trace fileを表示 Memory not freed: ----------------- Address Size Caller 0x0804a388 0xa at /home/fuz/Desktop/linux_system_programming/free.c:13
13行目で確保したbuf2が開放されていない
13 buf2 = (char*)malloc(10);