歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Linux C程序內存洩露檢測

對於程序員來說,最痛苦的就是內存的申請與釋放。內存洩露也是程序中經常遇到的問題。為了更好的定位內存洩露問題,我們有必要熟悉一些內存洩露的檢測工具。今天主要找到了以下四個內存檢測工具,使用起來都比較方便。

valgrind

安裝valgrind,執行下列程序

#include <stdlib.h>

void func()
{
        int *p = malloc(10*sizeof(int));
        p[10] = 0;
}

int main()
{
        func();
        return 0;
}

編譯:
gcc -g -o valgrindtst valgrindtst.c

執行內存檢測:

valgrind --tool=memcheck -leak-check=full ./valgrindtst

內存檢測結果:

==19896== Memcheck, a memory error detector
==19896== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==19896== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info
==19896== Command: ./valgrindtst
==19896==
==19896== Invalid write of size 4
==19896== at 0x80483DF: func (valgrindtst.c:6)
==19896== by 0x80483F1: main (valgrindtst.c:11)
==19896== Address 0x401a050 is 0 bytes after a block of size 40 alloc'd
==19896== at 0x40072D5: malloc (vg_replace_malloc.c:291)
==19896== by 0x80483D5: func (valgrindtst.c:5)
==19896== by 0x80483F1: main (valgrindtst.c:11)
==19896==
==19896==
==19896== HEAP SUMMARY:
==19896== in use at exit: 40 bytes in 1 blocks
==19896== total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==19896==
==19896== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==19896== at 0x40072D5: malloc (vg_replace_malloc.c:291)
==19896== by 0x80483D5: func (valgrindtst.c:5)
==19896== by 0x80483F1: main (valgrindtst.c:11)
==19896==
==19896== LEAK SUMMARY:
==19896== definitely lost: 40 bytes in 1 blocks
==19896== indirectly lost: 0 bytes in 0 blocks
==19896== possibly lost: 0 bytes in 0 blocks
==19896== still reachable: 0 bytes in 0 blocks
==19896== suppressed: 0 bytes in 0 blocks
==19896==
==19896== For counts of detected and suppressed errors, rerun with: -v
==19896== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 12 from 8)

檢測到內存洩露與數組越界的錯誤

Copyright © Linux教程網 All Rights Reserved