2012년 2월 15일 수요일

프로그램의 메모리 누수(Memory Leak) 체크


리눅스 프로그램에서의 메모리 누수 체크를 위한 방법에 대해 알아보자.
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. int main()  
  4. {  
  5.     char *str = (char*) malloc(1024);  
  6.     printf("flsdkjfslkjfsdklfj\n\n\n");  
  7.     printf("\n\n");  
  8.     return 0;  
  9. }  
컴파일( -g 옵션을 넣어야 파일과 라인을 알수 있다. 그리고 -o옵션보다 먼저 써줘야 한다.)
gcc -g -o test test.c

valgrind --tool=memcheck --leak-check=yes --show-reachable=yes ./test
하면
==17708==
==17708== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 1)
==17708== malloc/free: in use at exit: 1,024 bytes in 1 blocks.
==17708== malloc/free: 1 allocs, 0 frees, 1,024 bytes allocated.
==17708== For counts of detected errors, rerun with: -v
==17708== searching for pointers to 1 not-freed blocks.
==17708== checked 59,020 bytes.
==17708==
==17708== 1,024 bytes in 1 blocks are definitely lost in loss record 1 of 1
==17708==    at 0x4021620: malloc (vg_replace_malloc.c:149)
==17708==    by 0x80483D0: main (test.c:6) ==17708==
==17708== LEAK SUMMARY:
==17708==    definitely lost: 1,024 bytes in 1 blocks.
==17708==      possibly lost: 0 bytes in 0 blocks.
==17708==    still reachable: 0 bytes in 0 blocks.
==17708==         suppressed: 0 bytes in 0 blocks.


출력내용중 빨간색부분이 Memory 누수가 발생한 부분이다.
소스파일 test.c의 여섯번째 라인에서 메모리 누수가 발생하였다는 것이고, 하나의 블록에서 총 1,024byte의 누수가 발생하였음을 알 수 있다.

출력내용을 파일에 저장하고자 할 경우에는 "--log-file"옵션을 사용한다.

valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --log-file="./valgrind_log" ./test
1. Valgrind 설치

wget http://www.valgrind.org/downloads/valgrind-3.3.0.tar.bz2(새 창으로 열기)
tar xvfj valgrind-3.3.0.tar.bz2
cd valgrind-3.3.0
./configure
make
make install

2. Valgrind 테스트
valgrind --leak-check=yes main

3. 간단 실행법
valgrind --tool=memcheck --leak-check=full [프로그램] [실행인자들...]



출처 URL : http://dolba.net/tt/k2club/1994

댓글 없음:

댓글 쓰기