시스템 환경
- Ubuntu 22.10 kinetic
간단한 소개
Valgrind는 Linux용 디버깅 도구 모음으로, 프로그램의 메모리 누수, 불법 읽기/쓰기 등의 문제를 감지하는 데 자주 사용됩니다.
위키백과 - Valgrind - Wikipedia
이 글에서는 주로 Memcheck를 다루며, 프로그램의 메모리 누수 상황을 확인하는 데 사용할 수 있습니다.
Valgrind 설치
공식 다운로드 페이지 - Valgrind Download
BASH
sudo apt update && apt full-upgrade -y
sudo apt install valgrind -y
valgrind --version
사용 방법
BASH
valgrind ./<filename>
valgrind --leak-check=<no|summary|yes|full> [default: summary]
일반적인 오류
1. 불법 읽기/쓰기 오류
C
#include <stdio.h>
int main(){
int *ptr = 0;
*ptr = 0;
return 0;
}
BASH
gcc -g -O0 test.c -o test
./test
[1] 7453 segmentation fault (core dumped) ./test
valgrind ./test
==7484== Memcheck, a memory error detector
==7484== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==7484== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==7484== Command: ./test
==7484==
==7484== Invalid write of size 4
==7484== at 0x10913D: main (test.c:4)
==7484== Address 0x0 is not stack'd, malloc'd or (recently) free'd
2. 초기화되지 않은 값 접근
CodeBlock Loading...
CodeBlock Loading...
3. 시스템 호출에서 초기화되지 않았거나 주소 지정이 불가능한 값 사용
CodeBlock Loading...
CodeBlock Loading...
4. 불법 메모리 해제
CodeBlock Loading...
CodeBlock Loading...
5. 연산자 불일치
malloc/calloc/realloc/valloc/memalign으로 할당한 경우 반드시 free를 사용하여 해제해야 합니다.
new로 할당한 경우 반드시 delete를 사용하여 해제해야 합니다.
new[]로 할당한 경우 반드시 delete[]를 사용하여 해제해야 합니다.
Linux에서 이러한 프로그램을 실행해도 문제가 발생하지 않을 수 있지만, 다른 플랫폼에서는 크래시가 발생할 수 있습니다.
CodeBlock Loading...
CodeBlock Loading...
6. 메모리 중복 오류
(Memory Overlapping Error)
memcpy, strcpy, strncpy, strcat, strncat 사용 시 발생할 수 있는 메모리 중복 오류입니다.
CodeBlock Loading...
CodeBlock Loading...
7. 의심스러운 인자 값
(Fishy argument values)
CodeBlock Loading...
CodeBlock Loading...
8. 메모리 누수 감지
CodeBlock Loading...
CodeBlock Loading...