valgrind를 이용한 메모리 디버깅
: valgrind는 할당되지 않은 포인터 변수에 값을 넣는 것, malloc과 free를 수행하며 dangling pointer가 발생되거나 이중 free가 발생되는 문제와 같이 memory leak, invalid memory reference 등의 메모리 관련 문제점을 찾아주는 도구이다.
: 다음은 이러한 valgrind를 어떻게 사용하는지를 나타내는 예제이다.
#include <stdlib.h>
#include <iostream>
using namespace std;
int main()
{
int *pInt = NULL;
int cnt = 100;
pInt = (int *)malloc(sizeof(int) * cnt);
for (int i = 0; i < cnt; i++) {
pInt[i] = i;
}
cout << pInt[cnt] << endl;
for (int i = 0; i < cnt; i++) {
free(&pInt[i]);
}
return 0;
}
Pre-requisite
valgrind를 사용하기 위해서는 해당 툴이 설치되어있어야 한다.
설치는 다음의 명령어를 통해 할 수 있다.
$ sudo apt install valgrind
이제 다음의 명령어를 통해 컴파일한다.
jay@jay-VirtualBox:~/tutorial/valgrind$ g++ -o memory -g memory.cpp
jay@jay-VirtualBox:~/tutorial/valgrind$ ls
memory memory.cpp
그 후, memory leak과 관련된 오류가 발생하였는지 다음의 명령어를 통해 알 수 있다. 이는 valgrind가 해당 프로그램을 수행시켜보며 메모리 관련된 문제가 발생하였는지를 판단하는 것이므로 test-case를 통해 memory leak을 판단하고자 할 때, test-case가 작성한 코드의 모든 범위와 조건들을 충족하는지에 따라 검출되는 버그가 다르다는 것에 유의하길 바란다.
jay@jay-VirtualBox:~/tutorial/valgrind$ valgrind --tool=memcheck --leak-check=yes --leak-resolution=high -v ./memory
==39434== Memcheck, a memory error detector
==39434== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==39434== Using Valgrind-3.15.0-608cb11914-20190413 and LibVEX; rerun with -h for copyright info
==39434== Command: ./memory
==39434==
--39434-- Valgrind options:
--39434-- --tool=memcheck
--39434-- --leak-check=yes
--39434-- --leak-resolution=high
--39434-- -v
...
==39604== 99 errors in context 2 of 2:
==39604== Invalid free() / delete / delete[] / realloc()
==39604== at 0x483CA3F: free (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==39604== by 0x1092AA: main (memory.cpp:19)
==39604== Address 0x4dafc84 is 4 bytes inside a block of size 400 free'd
==39604== at 0x483CA3F: free (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==39604== by 0x1092AA: main (memory.cpp:19)
==39604== Block was alloc'd at
==39604== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==39604== by 0x109214: main (memory.cpp:10)
'빌드&테스트도구 > 테스팅도구(gcov,gtest.' 카테고리의 다른 글
gtest - google에서 개발한 TC framework (0) | 2020.10.09 |
---|---|
lcov, genhtml - coverage 정보를 깔끔한 웹 페이지로 만들기 (0) | 2020.09.28 |
gcov - 커버리지 측정 (0) | 2020.09.26 |