Finding C++ Memory Leaks: Valgrind, AddressSanitizer,
이 글의 핵심
Detect heap leaks with Valgrind memcheck, ASan+LSan, and Visual Studio CRT debug heap. Common leak patterns: new/delete mismatch, exceptions, shared_ptr cycles, containers of raw pointers.
Tooling: [Valgrind](/en/blog/cpp-valgrind/ · ownership in C++: [smart pointers](/en/blog/cpp-smart-pointers/ · Rust contrast: [ownership](/en/blog/rust-series-02-ownership/.
Introduction: “Memory grows until OOM”
“The server runs for days, then dies”
A memory leak means you lose the last pointer to heap memory without freeing it. Long-running services eventually OOM.
// 실행 예제
void handle() {
int* p = new int[1000];
// forgot delete[]
}
This article covers:
- Five major leak causes
- Valgrind (Linux)
- AddressSanitizer + LeakSanitizer
- Visual Studio / CRT helpers
- Ten leak patterns and RAII fixes
- Production monitoring ideas
Table of contents
- What is a leak?
- Five major causes
- Valgrind
- AddressSanitizer
- Visual Studio heap
- Ten patterns
- RAII
- Production monitoring
- Summary
1. What is a memory leak?
Heap memory no longer reachable from any pointer in the program → cannot be freed → grows until limits. Contrast with intentional growth (e.g. a cache) where memory is still reachable.
2. Five major causes (overview)
- new/delete mismatch or missing
delete - Exception paths skipping manual cleanup
shared_ptrcycles- Containers of raw owning pointers without cleanup
- Singletons with raw
newand no teardown
3. Valgrind
g++ -g -std=c++17 -o myapp main.cpp
valgrind --leak-check=full --show-leak-kinds=all ./myapp
Interpret definitely lost vs still reachable (globals may be “reachable” at exit).
4. AddressSanitizer / LeakSanitizer
g++ -g -fsanitize=address -std=c++17 -o myapp main.cpp
export ASAN_OPTIONS=detect_leaks=1
./myapp
Visual Studio: enable AddressSanitizer in project settings (version-dependent).
5. Visual Studio / CRT
_CrtSetDbgFlag with _CRTDBG_LEAK_CHECK_DF in debug builds for leak dumps on exit.
6. Ten patterns (titles)
- Raw
newwithoutdelete - Exception before
delete→ RAII new[]paired with wrongdeletevector<T*>without deleting elementsshared_ptrcycle → weak_ptr- Conditional
deletepaths - Rule-of-five violations (double free / leak)
- Factory returning raw owning pointer without documented ownership
- Globals with manual
new - Thread stacks leaking thread-local
new
7. RAII
Acquire in constructor / release in destructor — unique_ptr, vector, file handles, locks.
8. Production monitoring
/proc/self/status VmRSS on Linux, custom allocation counters (carefully—global operator new hooks affect everything), periodic sanity checks against baselines.
Summary
Tool comparison
| Tool | Platform | Speed | Rebuild |
|---|---|---|---|
| Valgrind | Linux | Slow | No |
| ASan/LSan | Many | ~2× | Yes |
| VS heap | Windows | Fast | Debug helpers |
Rules
- Prefer
make_unique/make_sharedover rawnew. - Containers should usually own values or smart pointers, not raw pointers.
- Break shared_ptr cycles with weak_ptr.
- Run ASan/Valgrind in CI on tests.
Related posts (internal)
- Memory leaks (series)
- RAII
- Smart pointers
- Circular references
Keywords
memory leak, Valgrind, AddressSanitizer, LeakSanitizer, RAII, new delete
Practical tips
- Enable ASan on developer builds by default.
- Add Valgrind stage for release candidates on Linux.
- Review any returning raw owning pointer APIs.
Closing
Leaks are common but preventable: RAII, smart pointers, no cycles, and automated leak checks in CI. Next: Use-after-free and deeper Valgrind articles.
More related posts
자주 묻는 질문 (FAQ)
Q. 이 내용을 실무에서 언제 쓰나요?
A. Detect heap leaks with Valgrind memcheck, ASan+LSan, and Visual Studio CRT debug heap. Common leak patterns: new/delete … 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.
Q. 선행으로 읽으면 좋은 글은?
A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.
Q. 더 깊이 공부하려면?
A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.
같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- [C++ Valgrind: A Practical Memory Debugging Complete Guide](/en/blog/cpp-valgrind/
- [C++ Smart Pointers: unique_ptr, shared_ptr & Memory-Safe](/en/blog/cpp-smart-pointers/
- [Rust Ownership | Ownership, Borrowing, and Lifetimes](/en/blog/rust-series-02-ownership/
- C++ 메모리 누수 | 서버 다운시킨 실제 사례와 Valgrind로 찾는 5가지 패턴
- C++ RAII 완벽 가이드 | ‘Too many open files’ 장애 원인과 리소스 자동 관리
이 글에서 다루는 키워드 (관련 검색어)
C++, Memory leak, Valgrind, AddressSanitizer, LeakSanitizer, RAII, Debugging 등으로 검색하시면 이 글이 도움이 됩니다.