Writing Robust C++: Detecting and Avoiding Memory Issues

1. Why so many new projects pick Rust instead of C++
If you follow systems programming, you have noticed the trend: a growing share of new infrastructure — operating-system components, browsers, network services, command-line tools — is being written in Rust rather than C++. There are many reasons (a modern build system, a strong package ecosystem, expressive types), but the single most important one is memory safety.
The data is hard to ignore:
- Microsoft reported that ~70% of the security vulnerabilities they assign a CVE to are memory-safety issues.
- The Chromium team reported roughly the same ~70% of high-severity security bugs in Chrome are memory-unsafety bugs (use-after-free being the single largest category).
- Android's security team published similar numbers, and later showed that moving new code to memory-safe languages sharply reduced the vulnerability rate.
- National security agencies (CISA/NSA) have since publicly urged the industry to adopt memory-safe languages for new development.
Rust's appeal here is that its ownership model and borrow checker prevent most of these bugs at compile time — a whole class of errors simply cannot be expressed in safe Rust. C++, by design, gives you raw pointers, manual lifetime management, and unchecked buffer access. That power is exactly why C++ remains essential for performance-critical and existing systems — but it is also why C++ lets you write the bugs Rust forbids.
The reality for most of us, though, is that C++ is not going away. There are billions of lines of it in production, and rewriting all of it in Rust is neither practical nor desirable. So the pragmatic question is not "C++ or Rust?" but: As C++ developers, how do we detect and avoid memory issues so we can write> robust programs?
That is what this article is about.
2. The memory problems C++ lets you make
Memory bugs have plagued C++ since its beginning. They fall into a handful of recognizable categories:
- Memory leak — allocated memory is never freed. Leads to growing memory use and eventual exhaustion.
- Heap buffer overflow — read/write past the end of a heap allocation. Leads to corruption, crashes, exploits.
- Stack buffer overflow — read/write past a local array. Leads to corruption and control-flow hijacking.
- Global buffer overflow — read/write past a static/global array. Leads to corruption.
- Use-after-free — access memory after it was freed. Leads to crashes and exploitable undefined behavior.
- Double free — free the same block twice. Leads to heap corruption.
- Uninitialized read — read memory that was never written. Leads to non-deterministic behavior and information leaks.
- Alloc/dealloc mismatch — e.g. new[] freed with scalar delete. Leads to undefined behavior, partial destruction, leaks.
- Use-after-return — use a pointer to an expired stack frame. Leads to crashes and corruption.
The insidious part is that most of these are undefined behavior that often "works" by accident — the program appears fine in testing and corrupts memory in production. This is precisely why we need tools that make these bugs deterministic and visible.
3. The tools
Over the decades, a set of well-known tools emerged to fight these bugs. Before listing them, it helps to understand that they come in two fundamentally different philosophies**.
3.1 Two philosophies
Compile-time instrumentation (the sanitizers). You recompile your code with a special flag (e.g. `-fsanitize=address`). The compiler inserts checks and surrounds allocations with poisoned "redzones," backed by a shadow-memory map. Result: fast (~2× slowdown) and precise, but it needs your source and a rebuild, and it can only see what it instrumented.
Dynamic binary instrumentation (Valgrind, Dr. Memory). The tool runs your *unmodified* binary on a synthetic CPU, tracking the state of every byte of memory at runtime. Result: no recompile, catches more (including uninitialized reads), but much slower (~10–50×).
Neither strictly dominates — they are complementary, and serious projects use both.
3.2 The tools at a glance
- MSVC AddressSanitizer (`/fsanitize=address`) — Microsoft's ASan port. Detects corruption (overflows, use-after-free, double-free). Does not detect leaks (LeakSanitizer is not ported to Windows).
- GCC/Clang AddressSanitizer — the original ASan on Linux/macOS. Bundles LeakSanitizer, so it catches corruption and leaks in one build.
- LeakSanitizer (LSan) — the leak-detection component of ASan (Linux).
- MemorySanitizer (MSan) — Clang/Linux only; detects uninitialized reads, which ASan cannot.
- CRT Debug Heap (`_CrtSetDbgFlag`, `_CrtDumpMemoryLeaks`) — the built-in Windows debug allocator. Reports leaks with allocation numbers, and flags heap corruption/double-free (as generic "heap corruption").
- Visual Studio Diagnostic Tools — interactive memory-usage snapshots; diff two snapshots to find leaks with allocation stacks.
- Application Verifier + PageHeap — Microsoft runtime verification; guard pages make heap overflow / use-after-free fault *immediately* on a normal build.
- UMDH — Windows tool that diffs heap allocation stacks to find leaks, **without recompiling**.
- Dr. Memory — open-source, Valgrind-style tool for Windows and Linux. Detects overflows, use-after-free, double-free, uninitialized reads, and leaks — all in one run, no recompile. -- but it is too old to can be used on new OS.
- Valgrind (Memcheck) — the classic Linux/macOS tool. Detects heap corruption, use after-free, leaks, and uninitialized reads; weak on stack/global overflows; no recompile needed.
3.3 Platform support
Each entry lists: platforms supported, whether a recompile is required, and the approximate slowdown.
- MSVC ASan — Windows only. Recompile: yes. Slowdown: ~2x.
- Clang/GCC ASan — Linux and macOS (partial on Windows via clang). Recompile: yes. Slowdown: ~2x.
- LeakSanitizer — Linux (partial on macOS). Recompile: yes. Slowdown: small.
- MemorySanitizer — Linux, Clang only. Recompile: yes. Slowdown: ~3x.
- CRT Debug Heap — Windows only. Recompile: no special flags (needs a `_DEBUG` build and a few lines of code). Slowdown: low.
- VS Diagnostic Tools — Windows only. Recompile: no. Slowdown: low.
- App Verifier + PageHeap — Windows only. Recompile: no. Slowdown: low CPU, high memory.
- UMDH — Windows only. Recompile: no. Slowdown: moderate.
- Dr. Memory — Windows and Linux (partial on macOS). Recompile: no. Slowdown: ~10x.
- Valgrind (Memcheck) — Linux (partial on macOS). Recompile: no. Slowdown: ~20-50x.
3.4 Detection capabilities
Which memory issues each tool can catch:
- MSVC ASan — catches heap/stack/global overflow, use-after-free, double-free, and (with an option) alloc/dealloc mismatch. Misses leaks and uninitialized reads.
- Clang/GCC ASan — catches all of the above plus leaks (via bundled LSan). Misses uninitialized reads.
- LeakSanitizer — catches leaks only.
- MemorySanitizer — catches uninitialized reads only.
- CRT Debug Heap — catches leaks and double-free; catches heap overflow and use-after-free only weakly (at free time). Misses stack/global overflow and uninitialized reads.
- App Verifier + PageHeap — catches heap overflow, use-after-free, and double-free. Misses leaks, stack/global overflow, and uninitialized reads.
- Dr. Memory — catches leaks, heap overflow, use-after-free, double-free, uninitialized reads, and alloc/dealloc mismatch; stack/global overflow only partially.
- Valgrind (Memcheck) — catches leaks, heap overflow, use-after-free, double-free, uninitialized reads, and alloc/dealloc mismatch. Misses stack/global overflow.
(MSVC ASan's alloc/dealloc mismatch check needs ASAN_OPTIONS=alloc_dealloc_mismatch=1.)
The gaps are clear: no single tool catches everything on any one platform. ASan is fast and covers corruption + stack/global, but misses leaks (on Windows) and uninitialized reads (everywhere). Valgrind/Dr. Memory cover uninitialized reads and leaks but are slow and weak on stack overflows. The practical answer is to combine tools.
4. Recommended setups
Windows: CRT Debug Heap + MSVC ASan + Dr. Memory
- CRT Debug Heap — your everyday, zero-cost leak detector. A few lines in `main()` and every Debug run reports leaks on exit.
- MSVC ASan — a separate build config for corruption (overflow, use-after-free, double-free). Fast, precise stacks. Cannot share a build with the CRT debug heap — they both replace the allocator.
- Dr. Memory — the comprehensive sweep when you need everything at once, including uninitialized reads, on an unmodified binary. Use before releases or when a bug won't reproduce under the others. -- Not Work on New OS.
Linux: GCC/Clang ASan + Dr. Memory / Valgrind
- GCC/Clang ASan (+LSan) — the default daily driver: corruption and leaks in one fast build.
- Valgrind (Memcheck) — add uninitialized-read detection and run on binaries you cannot rebuild. (For uninitialized reads specifically, Clang's MemorySanitizer is the fast alternative, if you can instrument all dependencies.)
5. Avoiding the problems in the first place
Detection is the safety net. The real goal is to not create the bugs at all. C++ has matured enormously here — modern C++ lets you avoid most manual memory management:
- Prefer RAII over manual new/delete. Let destructors free resources deterministically. Every raw `new` is a leak waiting for an early `return` or exception.
- Use smart pointers. std::unique_ptr`for sole ownership, std::shared_ptr for shared ownership. std::make_unique/ std::make_shared avoid raw new entirely and are exception-safe.
- Use standard containers (std::vector , std::string, std::array) instead of raw arrays and hand-managed buffers. They own their memory and know their size.
- Follow the Rule of Zero. Design classes so they need no user-declared destructor/copy/move — let members (smart pointers, containers) manage everything. If you must write one, write all five (Rule of Five).
- Be careful with views. std::string_view and std::span do not own their data — never return one that outlives its backing storage.
- Prefer bounds-checked access in hot debugging paths (`.at()`, or containers over pointers). Avoid pointer arithmetic where an index or iterator will do.
- Watch object lifetimes and references. Never return a reference/pointer to a local; be explicit about who owns what and how long it lives.
- Turn on the compiler. Build with high warning levels (`/W4`, `-Wall -Wextra -Wconversion`) and treat warnings as errors. The compiler already catches things like "returning address of local variable."
- Add static analysis and sanitizers to CI. Run clang-tidy / MSVC analysis on every change, and run an ASan build in your test pipeline so regressions are caught automatically.
In short: write code where the ownership is obvious and the compiler/library manages memory for you — then use the tools to catch the cases that slip through.
6. Hands-on: exercising every issue with test_memory_issue.cpp
To make all of this concrete, we will write a simple test_memory_issue.cpp — a small harness that reproduces each memory bug behind its own subcommand. Because most tools abort on the first error, each bug is isolated and run one at a time:
test_memory_issue.cpp
// test_memory_issue.cpp
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
// CRT debug-heap leak reporting (MSVC Debug builds only, and NOT under ASan,
// since the two allocators conflict).
#if defined(_DEBUG) && !defined(__SANITIZE_ADDRESS__)
# define _CRTDBG_MAP_ALLOC
# include <crtdbg.h>
# define ENABLE_CRT_LEAK_CHECK 1
#define new new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#endif
// ASan reads its default options from this hook at startup, so the mismatch and
// use-after-return cases are caught without an ASAN_OPTIONS env var. The options
// string comes from CMake (ASAN_DEFAULT_OPTIONS). An explicit ASAN_OPTIONS env
// var still overrides it. On Windows the symbol must be exported so the ASan
// runtime DLL can find it.
#if defined(__SANITIZE_ADDRESS__) && defined(ASAN_DEFAULT_OPTIONS)
extern "C"
# if defined(_MSC_VER)
__declspec(dllexport)
# endif
const char* __asan_default_options()
{
return ASAN_DEFAULT_OPTIONS;
}
#endif
// Keep the optimizer from deleting the very bug we are trying to trigger.
#if defined(_MSC_VER)
# define NOINLINE __declspec(noinline)
#else
# define NOINLINE __attribute__((noinline))
#endif
// A volatile sink so reads/writes are observable side effects and can't be
// optimized away.
static volatile int g_sink;
// -----------------------------------------------------------------------------
// 1 Leak: allocate and never free. Detected by CRT heap dump / LSan / Dr.Memory.
NOINLINE void case_leak()
{
int* p = new int[64];
p[0] = 42;
g_sink = p[0];
// no delete[] -> leak
std::cout << "leaked a 64-int block\n";
}
// 2 Heap buffer overflow: write one past the end of a heap allocation.
NOINLINE void case_heap_overflow(int n)
{
int* p = new int[n]; // n comes from argc so size is not a constant
for (int i = 0; i <= n; ++i) // <= writes p[n] : one past the end
p[i] = i;
g_sink = p[0];
delete[] p;
}
// 3 Stack buffer overflow: write past a local array. ASan only (not Valgrind).
NOINLINE void case_stack_overflow(int idx)
{
int buf[8];
buf[idx] = 123; // idx == 8 -> out of bounds
g_sink = buf[0];
}
// 4 Global buffer overflow: write past a static array. ASan only.
static int g_global[8];
NOINLINE void case_global_overflow(int idx)
{
g_global[idx] = 123; // idx == 8 -> out of bounds
g_sink = g_global[0];
}
// 5 Use-after-free: read/write memory after it was freed.
NOINLINE void case_use_after_free()
{
int* p = new int[16];
p[0] = 7;
delete[] p;
g_sink = p[0]; // read freed memory
}
// 6 Double free: free the same block twice.
NOINLINE void case_double_free()
{
int* p = new int(5);
delete p;
delete p; // second free
}
// 7 Uninitialized read: read memory that was never written. ASan misses this;
// Valgrind/MSan/Dr.Memory catch it.
NOINLINE void case_uninitialized()
{
int* p = new int[4]; // not value-initialized
if (p[2] == 0x1234) // read of uninitialized value
g_sink = 1;
else
g_sink = 2;
delete[] p;
std::cout << "read uninitialized value, sink=" << g_sink << "\n";
}
// 8 alloc/dealloc mismatch: new[] freed with scalar delete. UB.
NOINLINE void case_alloc_dealloc_mismatch()
{
int* p = new int[8]; // array new
g_sink = p[0] = 1;
delete p; // scalar delete : mismatch
}
// 9 Use-after-return: return a pointer to a local and dereference it.
NOINLINE int* leak_local_address()
{
int local = 99;
g_sink = local;
return &local; // dangling once the function returns
}
NOINLINE void case_use_after_return()
{
int* p = leak_local_address();
g_sink = *p; // read of a destroyed stack frame
}
// -----------------------------------------------------------------------------
// All case names, in run order. The non-crashing cases come first so that a
// "run all" gets as far as possible before a crashing case ends the process.
static const char* const kAllCases[] = {
"leak",
"uninitialized",
"heap-overflow",
"stack-overflow",
"global-overflow",
"use-after-free",
"alloc-dealloc-mismatch",
"use-after-return",
};
// Runs one case. Returns false if the name is unknown.
static bool dispatch(const std::string& c)
{
if (c == "leak") case_leak();
else if (c == "heap-overflow") case_heap_overflow(2);
else if (c == "stack-overflow") case_stack_overflow(8);
else if (c == "global-overflow") case_global_overflow(8);
else if (c == "use-after-free") case_use_after_free();
else if (c == "double-free") case_double_free();
else if (c == "uninitialized") case_uninitialized();
else if (c == "alloc-dealloc-mismatch") case_alloc_dealloc_mismatch();
else if (c == "use-after-return") case_use_after_return();
else return false;
return true;
}
static void usage(const char* prog)
{
std::cout <<
"usage: " << prog << " [case]\n"
" with no argument, every case runs in sequence\n"
" cases: leak, heap-overflow, stack-overflow, global-overflow,\n"
" use-after-free, double-free, uninitialized,\n"
" alloc-dealloc-mismatch, use-after-return\n";
}
int main(int argc, char* argv[])
{
#ifdef ENABLE_CRT_LEAK_CHECK
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
// By default the leak dump goes to the debugger via OutputDebugString and is
// invisible on a plain console. Redirect it to stderr so it shows either way.
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
//_CrtSetBreakAlloc(168);
#endif
if (argc >= 2)
{
const std::string c = argv[1];
if (!dispatch(c)) { usage(argv[0]); return 1; }
std::cout << "case '" << c << "' finished\n";
return 0;
}
for (const char* name : kAllCases)
{
std::cout << "\n=== " << name << " ===\n";
dispatch(name);
}
std::cout << "\nall cases finished\n";
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(MemoryTest)
# Force to use C++ 20 and disable extensions
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
option(ENABLE_ASAN "Enable address sanitizer" OFF)
if(ENABLE_ASAN)
if (MSVC)
# Note: MSVC ASan does not detect memory leaks (use the CRT debug heap).
# /fsanitize-address-use-after-return is required for use-after-return
# detection on MSVC, but on toolset 14.38 it produces false positives
# inside the STL (std::string / iostream) that abort before user code
# runs, so it is intentionally left off. Use-after-return is still caught
# at build time via warning C4172; for runtime coverage use Clang/Linux ASan.
add_compile_options(/fsanitize=address)
string(REPLACE "/RTC1" "" CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}")
add_link_options(/INCREMENTAL:NO)
else()
add_compile_options(-fsanitize=address -fno-omit-frame-pointer)
add_link_options(-fsanitize=address)
endif()
endif()
# Bake ASan runtime options into the test binary so the alloc/dealloc-mismatch
# and use-after-return cases are detected without setting ASAN_OPTIONS by hand.
# The source picks this up via the __asan_default_options() hook.
if(ENABLE_ASAN)
target_compile_definitions(test_memory_issue PRIVATE
"ASAN_DEFAULT_OPTIONS=\"alloc_dealloc_mismatch=1:detect_stack_use_after_return=1\"")
endif()
add_executable(test_memory_issue test_memory_issue.cpp)
CMakePresets.json
{
"version": 6,
"configurePresets": [
{
"name": "default",
"hidden": true,
"binaryDir": "${sourceDir}/build/${presetName}",
"cacheVariables": {
"CMAKE_INSTALL_PREFIX": "${sourceDir}/build/install/${presetName}"
}
},
{
"name": "dev",
"hidden": true
},
{
"name": "windows",
"inherits": "default",
"generator": "Visual Studio 17 2022",
"cacheVariables": {
"ENABLE_ASAN": "ON"
}
},
{
"name": "linux",
"inherits": "default",
"cacheVariables": {
"ENABLE_ASAN": "ON"
}
},
{
"name": "dev-windows",
"inherits": [ "dev", "windows" ]
},
{
"name": "dev-linux",
"inherits": [ "dev", "linux" ]
}
]
}Build on windows
cmake --preset=dev-windows
cmake --build ./build/dev-windowsNotes on running the ASan build:
- Inside Visual Studio the ASan runtime DLL is found automatically. From an external console, launch from a Developer Command Prompt (or copy `clang_rt.asan_dynamic-x86_64.dll` next to the exe), or you will get a "DLL not found" error.
- For the mismatch case, set `ASAN_OPTIONS = alloc_dealloc_mismatch = 1`.
- For use-after-return, set `ASAN_OPTIONS = detect_stack_use_after_return = 1`.
Build on linux
cmake --preset=dev-linux
cmake --build ./build/dev-linuxRun and check the output
6.1 Memory leak
Plain Debug build (CRT Debug Heap). Change ENABLE_ASAN in preset to OFF
Output:
Detected memory leaks!
Dumping objects ->
{168} normal block at 0x000001C7407580B0, 256 bytes long.
Data: <* > 2A 00 00 00 CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.windows office doc : https://learn.microsoft.com/en-us/cpp/c-runtime-library/find-memory-leaks-using-the-crt-library?view=msvc-170
The memory allocation number, which is 168 in the example ,The block type, normal in the example. as the doc said if your program allocates memory using the C++ new operator ,
we need to relace new keywork by define #define new new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
then the file name and line number will be showed in output
xxx\test_memory_issue.cpp(32) : {168} normal block at 0x000001659C0180B0, 256 bytes long.
Data: <* > 2A 00 00 00 CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.The memory allocation number tells you when a leaked memory block was allocated, we can set a breakpoint here by _CrtSetBreakAlloc(168);
int main(int argc, char* argv[])
{
#ifdef ENABLE_CRT_LEAK_CHECK
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
// By default the leak dump goes to the debugger via OutputDebugString and is
// invisible on a plain console. Redirect it to stderr so it shows either way.
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetBreakAlloc(168);
#endif
then we can know the leak point

Linux Platform
GCC ASAN
=================================================================
==3666==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 256 byte(s) in 1 object(s) allocated from:
#0 0x76edb48fe6c8 in operator new[](unsigned long) ../../../../src/libsanitizer/asan/asan_new_delete.cpp:98
#1 0x55b0d9f1654f in case_leak() /xx/test_memory_issue.cppa:48
#2 0x55b0d9f16cf0 in dispatch /xx/test_memory_issue.cpp:150
#3 0x55b0d9f16fb8 in main /xx/test_memory_issue.cpp:188
#4 0x76edb402a1c9 in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
#5 0x76edb402a28a in __libc_start_main_impl ../csu/libc-start.c:360
#6 0x55b0d9f16464 in _start (/xx/build/dev-linux/test_memory_issue+0x3464) (BuildId: 9e08ead0b479e1d498956c395889b7658ac530d0)
SUMMARY: AddressSanitizer: 256 byte(s) leaked in 1 allocation(s).the GCC ASAN output is very clear, it indicates which line have caused this issue.
6.2 Heap buffer overflow
Windows Platform
MSVC ASAN:
==26068==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x11ebe1ca01f8 at pc 0x7ff6cd5d1237 bp 0x00204b7af3e0 sp 0x00204b7af3e8
WRITE of size 4 at 0x11ebe1ca01f8 thread T0
#0 0x7ff6cd5d1236 in case_heap_overflow(int) xxx\test_memory_issue.cpp:44
....
SUMMARY: AddressSanitizer: heap-buffer-overflow xxx\test_memory_issue.cpp:44 in case_heap_overflow(int)6.3 Stack buffer overflow
Both MSVC and GCC ASAN:
==57904==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x007e0feff470 at pc 0x7ff6cd5d13f9 bp 0x007e0feff410 sp 0x007e0feff418
WRITE of size 4 at 0x007e0feff470 thread T0
#0 0x7ff6cd5d13f8 in case_stack_overflow(int) xxx\test_memory_issue.cpp:53
...
SUMMARY: AddressSanitizer: stack-buffer-overflow xxx\test_memory_issue.cpp:53 in case_stack_overflow(int)6.4 Global buffer overflow
Both MSVC and GCC ASAN:
==52496==ERROR: AddressSanitizer: global-buffer-overflow on address 0x7ff6cd5e8f40 at pc 0x7ff6cd5d154c bp 0x002f9d0ff410 sp 0x002f9d0ff418
WRITE of size 4 at 0x7ff6cd5e8f40 thread T0
#0 0x7ff6cd5d154b in case_global_overflow(int) xxx\test_memory_issue.cpp:61
0x7ff6cd5e8f40 is located 0 bytes after global variable 'g_global' defined in 'test_memory_issue.cpp:58:11' (0x7ff6cd5e8f20) of size 32
SUMMARY: AddressSanitizer: global-buffer-overflow xxx\test_memory_issue.cpp:61 in case_global_overflow(int)6.5 Use-after-free
Both MSVC and GCC ASAN:
==63136==ERROR: AddressSanitizer: heap-use-after-free on address 0x1277df5a0080 at pc 0x7ff6cd5d16c4 bp 0x00ef449efa00 sp 0x00ef449efa08
READ of size 4 at 0x1277df5a0080 thread T0
#0 0x7ff6cd5d16c3 in case_use_after_free(void) xxx\test_memory_issue.cpp:71
...
SUMMARY: AddressSanitizer: heap-use-after-free xxx\test_memory_issue.cpp:71 in case_use_after_free(void)6.6 Double free
Both MSVC and GCC ASAN:
#1 0x7ff6cd5d17ac in case_double_free(void) xxx\test_memory_issue.cpp:79
#1 0x7ff6cd5d1793 in case_double_free(void) xxx\test_memory_issue.cpp:78
#1 0x7ff6cd5d16f9 in case_double_free(void) xxx\test_memory_issue.cpp:77
SUMMARY: AddressSanitizer: double-free xxx\test_memory_issue.cpp:79 in case_double_free(void)6.7 Uninitialized read
Both MSVC and GCC ASAN Can not delete this issue.
6.8 Alloc/dealloc mismatch
In Windows, alloc-dealloc-mismatch error detection is off by default. To enable it, set the environment variable set ASAN_OPTIONS = alloc_dealloc_mismatch = 1 before running your program
doc https://learn.microsoft.com/en-us/cpp/sanitizers/error-alloc-dealloc-mismatch?view=msvc-170
==48664==ERROR: AddressSanitizer: alloc-dealloc-mismatch (operator new [] vs operator delete) on 0x113ffcea00d0
#0 0x7ff7df229423 in operator delete(void *, unsigned __int64) D:\a\_work\1\s\src\vctools\asan\llvm\compiler-rt\lib\asan\asan_win_delete_scalar_size_thunk.cpp:41
#1 0x7ff7df22198c in case_alloc_dealloc_mismatch(void) xxx\test_memory_issue.cpp:116
#2 0x7ff7df221ccc in dispatch xxx\test_memory_issue.cpp:157
#3 0x7ff7df221f3e in main xxx\test_memory_issue.cpp:188
SUMMARY: AddressSanitizer: alloc-dealloc-mismatch xxx\test_memory_issue.cpp:116 in case_alloc_dealloc_mismatch(void)
==48664==HINT: if you don't care about these errors you may set ASAN_OPTIONS=alloc_dealloc_mismatch=0GCC ASAN can deleted this also
0x503000000070 is located 0 bytes inside of 32-byte region [0x503000000070,0x503000000090)
allocated by thread T0 here:
#0 0x72c8e7cfe6c8 in operator new[](unsigned long) ../../../../src/libsanitizer/asan/asan_new_delete.cpp:98
#1 0x6163d35abae5 in case_alloc_dealloc_mismatch() /xxxtest_memory_issue.cpp:114
#2 0x6163d35abdf5 in dispatch /xxx/test_memory_issue.cpp:1576.9 Use-after-return
This check requires code generation that's activated by an extra compiler option, /fsanitize-address-use-after-return, and by setting the environment variable ASAN_OPTIONS = detect_stack_use_after_return = 1.
more details check the official doc: https://learn.microsoft.com/en-us/cpp/sanitizers/error-stack-use-after-return?view=msvc-170
On windows it's unusable because it false-positives, so suggest no add this compile option.
use-after-return safety net is the compiler warning C4172: returning address of local variable — which already fires on leak_local_address() at build time, with zero false positives. That's actually the better tool for this specific bug class: it catches it before you even run at compile time.
add_compile_options(/fsanitize=address /fsanitize-address-use-after-re
turn)
For runtime use-after-return coverage, use Clang/Linux ASan, where detect_stack_use_after_return works cleanly (no compile flag needed, no STL noise).
GCC ASAN can detect this without false positives
=================================================================
==6779==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x55f5e0168cb7 bp 0x7ffeaa85a9c0 sp 0x7ffeaa85a9b0 T0)
==6779==The signal is caused by a READ memory access.
==6779==Hint: address points to the zero page.
#0 0x55f5e0168cb7 in case_use_after_return() /xxx/test_memory_issue.cpp:129
#1 0x55f5e0168e16 in dispatch /xxx/test_memory_issue.cpp:158
#2 0x55f5e0168fb8 in main /xxx/test_memory_issue.cpp:188
#3 0x75bdcf62a1c9 in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
#4 0x75bdcf62a28a in __libc_start_main_impl ../csu/libc-start.c:360
#5 0x55f5e0168464 in _start (/xxx/build/dev-linux/test_memory_issue+0x3464) (BuildId: 9e08ead0b479e1d498956c395889b7658ac530d0)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /hxxx/test_memory_issue.cpp:129 in case_use_after_return()
==6779==ABORTINGRun with Dr.Memory in Windows
Download and Install Dr. Memory :
https://drmemory.org/page_download.html
https://drmemory.org/page_install.html
unzip the packet then add the bin64 folder to system envrionment variables
run it
drmemory.exe -- .\test_memory_issue.exe leak On my computer it output:
Unable to load client library: dbghelp.dll: library initializer failed..>it seems not support my new win11 OS.
Run with Dr.Memory in Linux
/drmemory -- test_memory_issue leak
[1] 8891 floating point exception (core dumped) /home/hayden/soft/DrMemory-Linux-2.6.0/bin64/drmemory -- test_memory_issueIt seems Dr.Memory not able to work on my linux system as well. maybe it is too old the latest version is released 2022.
Run with Valgrind in Linux
Install valgrind
sudo apt install valgrind
Run it with command:
valgrind --tool=memcheck --leak-check=full ./test_memory_issueOutPut:
dev-linux git:(main) ✗ valgrind --tool memcheck --leak-check=full ./test_memory_issue
valgrind: memcheck: command not found
➜ dev-linux git:(main) ✗ valgrind --tool=memcheck --leak-check=full ./test_memory_issue
==10847== Memcheck, a memory error detector
==10847== Copyright (C) 2002-2022, and GNU GPL'd, by Julian Seward et al.
==10847== Using Valgrind-3.22.0 and LibVEX; rerun with -h for copyright info
==10847== Command: ./test_memory_issue
==10847==
=== leak ===
leaked a 64-int block
=== uninitialized ===
==10847== Conditional jump or move depends on uninitialised value(s)
==10847== at 0x10A57B: case_uninitialized() (test_memory_issue.cpp:103)
==10847== by 0x10A7AF: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:156)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847==
read uninitialized value, sink=2
=== heap-overflow ===
==10847== Invalid write of size 4
==10847== at 0x10A40D: case_heap_overflow(int) (test_memory_issue.cpp:60)
==10847== by 0x10A6F4: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:151)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847== Address 0x4e1f658 is 0 bytes after a block of size 8 alloc'd
==10847== at 0x48485C3: operator new[](unsigned long) (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==10847== by 0x10A3E3: case_heap_overflow(int) (test_memory_issue.cpp:58)
==10847== by 0x10A6F4: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:151)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847==
=== stack-overflow ===
=== global-overflow ===
=== use-after-free ===
==10847== Invalid read of size 4
==10847== at 0x10A4F8: case_use_after_free() (test_memory_issue.cpp:87)
==10847== by 0x10A76A: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:154)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847== Address 0x4e1f6a0 is 0 bytes inside a block of size 64 free'd
==10847== at 0x484BFA4: operator delete[](void*) (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==10847== by 0x10A4F3: case_use_after_free() (test_memory_issue.cpp:86)
==10847== by 0x10A76A: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:154)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847== Block was alloc'd at
==10847== at 0x48485C3: operator new[](unsigned long) (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==10847== by 0x10A4D2: case_use_after_free() (test_memory_issue.cpp:84)
==10847== by 0x10A76A: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:154)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847==
=== alloc-dealloc-mismatch ===
==10847== Mismatched new/delete size value: 4
==10847== at 0x484A5B9: operator delete(void*, unsigned long) (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==10847== by 0x10A62F: case_alloc_dealloc_mismatch() (test_memory_issue.cpp:116)
==10847== by 0x10A7D0: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:157)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847== Address 0x4e1f780 is 0 bytes inside a block of size 32 alloc'd
==10847== at 0x48485C3: operator new[](unsigned long) (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==10847== by 0x10A5FF: case_alloc_dealloc_mismatch() (test_memory_issue.cpp:114)
==10847== by 0x10A7D0: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:157)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847==
==10847== Mismatched free() / delete / delete []
==10847== at 0x484A61D: operator delete(void*, unsigned long) (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==10847== by 0x10A62F: case_alloc_dealloc_mismatch() (test_memory_issue.cpp:116)
==10847== by 0x10A7D0: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:157)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847== Address 0x4e1f780 is 0 bytes inside a block of size 32 alloc'd
==10847== at 0x48485C3: operator new[](unsigned long) (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==10847== by 0x10A5FF: case_alloc_dealloc_mismatch() (test_memory_issue.cpp:114)
==10847== by 0x10A7D0: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:157)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847==
=== use-after-return ===
==10847== Invalid read of size 4
==10847== at 0x10A692: case_use_after_return() (test_memory_issue.cpp:129)
==10847== by 0x10A7F1: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:158)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==10847==
==10847==
==10847== Process terminating with default action of signal 11 (SIGSEGV)
==10847== Access not within mapped region at address 0x0
==10847== at 0x10A692: case_use_after_return() (test_memory_issue.cpp:129)
==10847== by 0x10A7F1: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:158)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847== If you believe this happened as a result of a stack
==10847== overflow in your program's main thread (unlikely but
==10847== possible), you can try to increase the size of the
==10847== main thread stack using the --main-stacksize= flag.
==10847== The main thread stack size used in this run was 8388608.
==10847==
==10847== HEAP SUMMARY:
==10847== in use at exit: 75,025 bytes in 4 blocks
==10847== total heap usage: 9 allocs, 5 frees, 75,168 bytes allocated
==10847==
==10847== 256 bytes in 1 blocks are definitely lost in loss record 2 of 4
==10847== at 0x48485C3: operator new[](unsigned long) (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==10847== by 0x10A37E: case_leak() (test_memory_issue.cpp:48)
==10847== by 0x10A6CB: dispatch(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (test_memory_issue.cpp:150)
==10847== by 0x10A9D9: main (test_memory_issue.cpp:196)
==10847==
==10847== LEAK SUMMARY:
==10847== definitely lost: 256 bytes in 1 blocks
==10847== indirectly lost: 0 bytes in 0 blocks
==10847== possibly lost: 0 bytes in 0 blocks
==10847== still reachable: 74,769 bytes in 3 blocks
==10847== suppressed: 0 bytes in 0 blocks
==10847== Reachable blocks (those to which a pointer was found) are not shown.
==10847== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==10847==
==10847== Use --track-origins=yes to see where uninitialised values come from
==10847== For lists of detected and suppressed errors, rerun with: -s
==10847== ERROR SUMMARY: 7 errors from 7 contexts (suppressed: 0 from 0)
[1] 10847 segmentation fault (core dumped) valgrind --tool=memcheck --leak-check=full ./test_memory_issuevalgrind works well in linux system.
7. static analysis
All the tools we've used (ASan, CRT heap, Dr. Memory, Valgrind) are dynamic — they only find bugs on code that actually runs. Static analyzers inspect the source without running it. Every tool in Section 4 is **dynamic** — it only finds a bug on a code path that actually executes at runtime. Static analysis is the complement: it inspects the source without running it, so it can flag bugs in branches your tests never reach. (The plain compiler warning `C4172: returning address of local variable` that catches our use-after-return case is the simplest example — a real bug found at build time, before any tool runs.)
The main options, from free/built-in to commercial:
- Compiler warnings — the cheapest layer. Build with `/W4` (MSVC) or `-Wall -Wextra -Wconversion -Wshadow` (GCC/Clang) and treat them as errors.
- MSVC `/analyze` (Code Analysis) — built into Visual Studio. Catches buffer overruns and null derefs, and with the C++ Core Guidelines / Lifetime checkers it flags dangling pointers statically.
- GCC `-fanalyzer` (GCC 10+) — strong on memory bugs: it statically detects malloc/leak, double-free, use-after-free, and null-deref. Just add the flag: g++ -std=c++20 -fanalyzer -c test_memory_issue.cpp.
- Clang Static Analyzer (`scan-build`) and clang-tidy — path-sensitive analysis plus hundreds of lint checks (`clang-analyzer-*`, `bugprone-*`, `cppcoreguidelines-*`). Wire clang-tidy into CMake so every build lints: `set(CMAKE_CXX_CLANG_TIDY clang-tidy -checks=-*,clang-analyzer-*,bugprone-*)`.
- Cppcheck — lightweight standalone linter, easy to drop into CMake via `set(CMAKE_CXX_CPPCHECK cppcheck --enable=warning,style)`.
- Commercial / heavier — PVS-Studio, Coverity (free for open source),SonarQube, Klocwork; CodeQL for security-oriented queries.
Static analysis has false positives and cannot prove everything, so it does not replace the runtime tools — it runs *before* them, over all code including the paths tests never hit. The robust setup is both: static analysis in CI to scan everything, plus sanitizer runs over a good test suite to catch what executes.
Hight warning levels
#if(MSVC)
#add_compile_options(/W4 /WX)
#else()
#add_compile_options(-Wall -Wextra -Wconversion -Wshadow -Werror)
#endif()
Run Code Anaylize in VS2022
In the header of VS2022 -> Analyze -> Run Code Analysis -> Run Code Analysis on test_memory_issue
Output
Code analysis starting...
test_memory_issue.cpp
xxx\test_memory_issue.cpp(95) : warning C6001: Using uninitialized memory 'p'.: Lines: 93, 94, 95, 96, 95
xxx\test_memory_issue.cpp(116) : warning C6283: 'p' is allocated with array new [], but deleted with scalar delete.: Lines: 114, 116
Code analysis complete.Running MSVC `/analyze` on test_memory_issue.cpp shows this concretely — it flags two bugs at compile time, without executing anything:
Test gcc -fanalyzer
g++ -std=c++20 -fanalyzer -c test_memory_issue.cppcmake
add_compile_options(-fanalyzer)OutPut
test_memory_issue.cpp: In function ‘int* leak_local_address()’:
test_memory_issue.cpp:124:12: warning: address of local variable ‘local’ returned [-Wreturn-local-addr]
124 | return &local; // dangling once the function returns
| ^~~~~~
test_memory_issue.cpp:122:9: note: declared here
122 | int local = 99;
| ^~~~~
test_memory_issue.cpp: In function ‘void case_leak()’:
test_memory_issue.cpp:49:10: warning: dereference of possibly-NULL ‘p’ [CWE-690] [-Wanalyzer-possible-null-dereference]
49 | p[0] = 42;
| ~~~~~^~~~
‘int main(int, char**)’: events 1-2
|
| 173 | int main(int argc, char* argv[])
| | ^~~~
| | |
| | (1) entry to ‘main’
|......
| 185 | if (argc >= 2)
| | ~~
| | |
| | (2) following ‘true’ branch (when ‘argc > 1’)...
|
‘int main(int, char**)’: event 3
|
|cc1plus:
| (3): ...to here
|
‘int main(int, char**)’: event 4
|
| 187 | const std::string c = argv[1];
| | ^
| | |
| | (4) calling ‘std::__cxx11::basic_string<char>::basic_string<’ from ‘main’
|
+--> ‘constexpr std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with <template-parameter-2-1> = std::allocator<char>; _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’: events 5-8
|
|/usr/include/c++/13/bits/basic_string.h:641:7:
| 641 | basic_string(const _CharT* __s, const _Alloc& __a = _Alloc())
| | ^~~~~~~~~~~~
| | |
| | (5) entry to ‘std::__cxx11::basic_string<char>::basic_string<>’
|......
| 645 | if (__s == 0)
| | ~~
| | |
| | (6) following ‘false’ branch (when ‘__s’ is non-NULL)...
|......
| 648 | const _CharT* __end = __s + traits_type::length(__s);
| | ~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (7) ...to here
| | (8) calling ‘std::char_traits<char>::length’ from ‘std::__cxx11::basic_string<char>::basic_string<>’GCC -fanalyzer statically caught some of your bugs at compile time, more than MSVC /analyze did, but still have false positive report.
8. Conclusion
C++ will not adopt Rust's borrow checker, but that does not mean we have to ship memory bugs. The path to robust C++ is twofold:
1. Avoid the bugs by writing modern C++ — RAII, smart pointers, standard containers, clear ownership, and warnings-as-errors — so that most memory is never managed by hand.
2. Detect what slips through with a layered setup — and note that static analysis is part of *detection*, not just prevention:
- Windows: CRT Debug Heap (leaks) + MSVC ASan (corruption) + Dr. Memory (everything, including uninitialized reads), plus MSVC `/analyze`
- Linux: GCC/Clang ASan + LSan (corruption + leaks) + Dr. Memory / Valgrind (uninitialized reads, no-recompile), plus `-fanalyzer` / clang-tidy (static analysis)
Wire the static analyzers, an ASan build, and a leak check into CI so regressions are caught automatically, and reach for the dynamic-binary tools before releases. Do that, and you can keep the performance and control of C++ while closing most of the safety gap that is driving the industry toward Rust.
