본문 바로가기

Robotics/Software Tech.

valgrind를 이용한 c++ 메모리 누수(memory leak) 검사 방법


현재 본인의 개발 환경은 아래와 같다.


개발환경 : Eclipse CDT, GCC


프로그램을 구성하고 컴파일과 링크의 오류가 없어서 잘 동작하고 있는것만 같은 프로그램에서..반드시 체크해야 할 부분이 메모리 누수이다.

동적으로 메모리를 할당하고 해제하는 과정에서 제대로 처리를 하지 못해서 발생하거나, 사용하는 특정 라이브러리 자체에서 발생하고 있거나, 변수 캐스팅 오류등 다양한 원인에 의해서 프로그램이 종료될때 메모리를 제대로 시스템에 반환하지 못할경우에 어떤일이 발생할지 알수가 없게된다.


이번에 사용해본것은 valgrind라는 프로그램이다.


설치는


$ sudo apt-get install valgrind


로 하면 되고,


사용하는 방법은 실행 프로그램을 만들고, 실행을 아래와 같이 하면 된다.


$ valgrind --leak-check=yes 프로그램위치



결과(에러가 없을경우)는 다음과 같이 보여진다. 임의의 프로그램을 만들어서 테스트해봤다.



==21631== Memcheck, a memory error detector

==21631== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.

==21631== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info

==21631== Command: ./test

==21631== 

^C==21631== 

==21631== HEAP SUMMARY:

==21631==     in use at exit: 6,359 bytes in 16 blocks

==21631==   total heap usage: 100 allocs, 84 frees, 16,285 bytes allocated

==21631== 

==21631== LEAK SUMMARY:

==21631==    definitely lost: 0 bytes in 0 blocks

==21631==    indirectly lost: 0 bytes in 0 blocks

==21631==      possibly lost: 0 bytes in 0 blocks

==21631==    still reachable: 6,359 bytes in 16 blocks

==21631==         suppressed: 0 bytes in 0 blocks

==21631== Reachable blocks (those to which a pointer was found) are not shown.

==21631== To see them, rerun with: --leak-check=full --show-reachable=yes

==21631== 

==21631== For counts of detected and suppressed errors, rerun with: -v

==21631== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)




자세한 내용은 아래 페이지를 참고.


http://valgrind.org/docs/manual/quick-start.html#quick-start.intro



------------------------------------

(2014. 4. 25 추가)


valgrind를 사용할 때 옵션을 잘 활용해야 한다. 특히 shared library를 사용할 때 옵션에서 --trace-children=yes 옵션을 주지 않으면, 로드한 라이브러리내에서 사용한 메모리의 누수는 체크하지 않기 때문이다.


따라서, 별도의 shared library(*.so)를 프로그램내에서 동적으로 로드한다면, 반드시 --trace-children=yes 옵션을 주자.

즉,


$ valgrind --leak-check=full --trace-children=yes <체크할 프로그램>


으로 점검해야 한다.


저 옵션을 사용하지 않고 메모리 누수가 없다는 것을 확인했지만, 동적으로 라이브러리를 로드하는 부분에서 분명 해제하는 코드를 넣지 않았는데, 누수가 없다고 뜨길래 옵션을 살펴보니 저 옵션을 해줘야 누수가 체크되는 것을 확인했다.