본문으로 건너뛰기
Previous
Next
Finding C++ Memory Leaks: Valgrind, AddressSanitizer,

Finding C++ Memory Leaks: Valgrind, AddressSanitizer,

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

  1. What is a leak?
  2. Five major causes
  3. Valgrind
  4. AddressSanitizer
  5. Visual Studio heap
  6. Ten patterns
  7. RAII
  8. Production monitoring
  9. 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)

  1. new/delete mismatch or missing delete
  2. Exception paths skipping manual cleanup
  3. shared_ptr cycles
  4. Containers of raw owning pointers without cleanup
  5. Singletons with raw new and 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)

  1. Raw new without delete
  2. Exception before deleteRAII
  3. new[] paired with wrong delete
  4. vector<T*> without deleting elements
  5. shared_ptr cycleweak_ptr
  6. Conditional delete paths
  7. Rule-of-five violations (double free / leak)
  8. Factory returning raw owning pointer without documented ownership
  9. Globals with manual new
  10. Thread stacks leaking thread-local new

7. RAII

Acquire in constructor / release in destructorunique_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

ToolPlatformSpeedRebuild
ValgrindLinuxSlowNo
ASan/LSanMany~2×Yes
VS heapWindowsFastDebug helpers

Rules

  1. Prefer make_unique / make_shared over raw new.
  2. Containers should usually own values or smart pointers, not raw pointers.
  3. Break shared_ptr cycles with weak_ptr.
  4. Run ASan/Valgrind in CI on tests.


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.


자주 묻는 질문 (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 등으로 검색하시면 이 글이 도움이 됩니다.