<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://kobolinsapps.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://kobolinsapps.com/" rel="alternate" type="text/html" /><updated>2026-12-03T17:44:52+00:00</updated><id>https://kobolinsapps.com/feed.xml</id><title type="html">Kobolin’s Apps</title><subtitle>Small, native Mac utilities and notes on building software, by Colin Neilens</subtitle><author><name>Colin Neilens</name></author><entry><title type="html">Five small Mac apps I built to fix my own annoyances</title><link href="https://kobolinsapps.com/2026/12/02/five-small-mac-apps/" rel="alternate" type="text/html" title="Five small Mac apps I built to fix my own annoyances" /><published>2026-12-02T19:00:00+00:00</published><updated>2026-12-02T19:00:00+00:00</updated><id>https://kobolinsapps.com/2026/12/02/five-small-mac-apps</id><content type="html" xml:base="https://kobolinsapps.com/2026/12/02/five-small-mac-apps/"><![CDATA[<p>Over the past few weeks I’ve turned five little utilities I wrote for myself into proper Mac apps that anyone can buy. Each one fixes a single everyday annoyance, lives quietly in the menu bar or along the edge of the screen, and costs $1.99 once, with a 7-day free trial.</p>

<p>Here’s what each one does, and why I built it.</p>

<h2 id="snipsational-one-shortcut-for-every-screenshot">Snipsational: one shortcut for every screenshot</h2>

<p><a href="/snipsational/"><img src="/snipsational/images/toolbar-light.jpg" alt="The Snipsational capture toolbar over a sample desktop" /></a></p>

<p>The Mac’s screenshot tool frustrated me: a different shortcut for every kind of capture, nothing copied to the clipboard, and a preview that disappeared before I could do anything with it. I wanted what I’d had on Windows: one shortcut and a toolbar with every mode.</p>

<p><a href="/snipsational/">Snipsational</a> is that. Press ⇧⌘4 and pick rectangle, freeform, window, full screen or a screen recording. The snip is already on your clipboard, saved to a folder, and open in an editor with arrows, highlights, text recognition and one-click redaction of email addresses, phone numbers and card numbers.</p>

<h2 id="screenknob-your-monitors-buttons-in-the-menu-bar">ScreenKnob: your monitor’s buttons, in the menu bar</h2>

<p><a href="/screenknob/"><img src="/screenknob/images/flyout-light.jpg" alt="The ScreenKnob menu bar panel with sliders for several monitors" /></a></p>

<p>The brightness keys on a Mac only work on the built-in screen. For an external monitor, you end up reaching behind it for its buttons.</p>

<p><a href="/screenknob/">ScreenKnob</a> talks to each monitor over its own cable, using a standard called DDC/CI, and changes its real brightness, contrast, volume and input from the menu bar. You can link brightness across every screen, save profiles such as “Daytime” and “Evening”, and script it from the command line.</p>

<h2 id="taskdeck-the-taskbar-i-missed">TaskDeck: the taskbar I missed</h2>

<p><a href="/taskdeck/"><img src="/taskdeck/images/taskbar-light.jpg" alt="TaskDeck's taskbar along the bottom of a Mac screen" /></a></p>

<p>I was a Windows user for a long time and loved the old taskbar: a button for every window, and a Quick Launch bar with my favourite apps one click away. When I moved to the Mac, the Dock never felt the same, and none of the alternatives worked quite the way I wanted.</p>

<p><a href="/taskdeck/">TaskDeck</a> adds that taskbar to macOS, on every display: one button per window that you can drag into your own order, a Start menu, Quick Launch, a system tray with a keep-awake switch, and a full-screen app launcher.</p>

<h2 id="displayhop-move-a-whole-app-to-another-monitor">DisplayHop: move a whole app to another monitor</h2>

<p><a href="/displayhop/"><img src="/displayhop/images/menu-light.png" alt="DisplayHop's menu in the Mac menu bar" /></a></p>

<p>I work across several monitors, and I kept moving whole apps between them: every editor window to the big screen for focused work, then back again for a meeting. macOS makes you drag each window separately.</p>

<p><a href="/displayhop/">DisplayHop</a> moves every window of the app you’re using to your next display with one keyboard shortcut, keeping the layout you had.</p>

<h2 id="magicermouse-right-clicks-that-stay-right-clicks">MagicerMouse: right clicks that stay right clicks</h2>

<p><a href="/magicermouse/"><img src="/magicermouse/images/live-view.png" alt="MagicerMouse's live view of touches on a Magic Mouse" /></a></p>

<p>I rest my index finger on my Magic Mouse while I right-click. Anyone who does that knows the result: the Mac reads it as a left click, and you have to lift your finger every time you want a menu. When I recorded my own clicks, macOS got none of my resting-finger right clicks right.</p>

<p><a href="/magicermouse/">MagicerMouse</a> learns how you hold the mouse and corrects the click before any app sees it.</p>

<h2 id="what-they-have-in-common">What they have in common</h2>

<ul>
  <li><strong>$1.99 each, one-time.</strong> No subscription. A license works on up to 3 of your Macs.</li>
  <li><strong>A 7-day free trial</strong> of every app, with nothing to sign up for.</li>
  <li><strong>Signed and notarised by Apple</strong>, so they open normally, and they update themselves.</li>
  <li><strong>Your data stays on your Mac.</strong> None of the apps uploads what you do; the privacy page for each app lists the few small things that go online, such as checking a license and checking for updates.</li>
  <li><strong>Feedback goes straight to me.</strong> Each app has a <em>Send Feedback…</em> item in its menu, and I read everything.</li>
</ul>

<p>You can see all five on the <a href="/">home page</a>. If one of them fixes something that bugs you too, I’d love to hear about it.</p>

<p>— Colin</p>]]></content><author><name>Colin Neilens</name></author><category term="apps" /><category term="mac" /><summary type="html"><![CDATA[Over the past few weeks I’ve turned five little utilities I wrote for myself into proper Mac apps that anyone can buy. Each one fixes a single everyday annoyance, lives quietly in the menu bar or along the edge of the screen, and costs $1.99 once, with a 7-day free trial.]]></summary></entry><entry><title type="html">C++ Debugging Insights: the series</title><link href="https://kobolinsapps.com/2026/01/17/cpp-debugging-insights/" rel="alternate" type="text/html" title="C++ Debugging Insights: the series" /><published>2026-01-17T12:00:00+00:00</published><updated>2026-01-17T12:00:00+00:00</updated><id>https://kobolinsapps.com/2026/01/17/cpp-debugging-insights</id><content type="html" xml:base="https://kobolinsapps.com/2026/01/17/cpp-debugging-insights/"><![CDATA[<p>This series explores the mindset and systematic approaches that senior engineers use to tackle complex debugging challenges.</p>

<h2 id="the-posts">The posts</h2>

<p>There are four parts:</p>

<ol>
  <li><a href="/2026/01/14/debugging-cpp-applications/"><strong>Debugging C++ Applications: A Senior Engineer’s Guide</strong></a> - Learn the fundamental mindset and systematic process for debugging complex C++ issues</li>
  <li><a href="/2026/01/15/debugging-memory-corruption/"><strong>Debugging Memory Corruption Like a Senior Engineer</strong></a> - Deep dive into memory corruption bugs, AddressSanitizer, and undefined behavior</li>
  <li><a href="/2026/01/16/debugging-memory-corruption-part3/"><strong>Debugging Memory Corruption and Crashes (Part 3)</strong></a> - Practical case studies using LLDB, WinDbg, and VS Code debuggers</li>
  <li><a href="/2026/01/17/advanced-debugging-case-studies/"><strong>Advanced Debugging Case Studies</strong></a> - Tackle heap corruption, buffer overflows, alignment issues, and multithreading bugs</li>
</ol>]]></content><author><name>Colin Neilens</name></author><category term="cpp" /><category term="debugging" /><summary type="html"><![CDATA[This series explores the mindset and systematic approaches that senior engineers use to tackle complex debugging challenges.]]></summary></entry><entry><title type="html">Advanced Debugging Case Studies in C++</title><link href="https://kobolinsapps.com/2026/01/17/advanced-debugging-case-studies/" rel="alternate" type="text/html" title="Advanced Debugging Case Studies in C++" /><published>2026-01-17T10:00:00+00:00</published><updated>2026-01-17T10:00:00+00:00</updated><id>https://kobolinsapps.com/2026/01/17/advanced-debugging-case-studies</id><content type="html" xml:base="https://kobolinsapps.com/2026/01/17/advanced-debugging-case-studies/"><![CDATA[<p>In this final installment of our C++ debugging series, we’ll dive into
some truly gnarly bugs that even seasoned developers struggle with.
We’ll tackle <strong>heap corruption</strong>, <strong>buffer overflows</strong>, <strong>memory
alignment issues</strong>, <strong>sneaky undefined behavior</strong> (like ODR violations
and integer overflow), and <strong>multithreading nightmares</strong> (race
conditions, data corruption, deadlocks). For each case study, we’ll walk
through the senior debugging mindset step-by-step. You’ll see how to use
<strong>AddressSanitizer (ASan)</strong> and <strong>UndefinedBehaviorSanitizer (UBSan)</strong>
to catch errors, and then leverage powerful debuggers – <strong>LLDB
(macOS)</strong>, <strong>WinDbg (Windows)</strong>, <strong>VS Code + CodeLLDB (macOS)</strong>, and
<strong>VS Code + CppDbg (Windows)</strong> – to trace problems down to the root
cause. Let’s get started!</p>

<h2 id="1-heap-corruption-case-study">1. Heap Corruption Case Study</h2>

<p>Heap corruption bugs occur when you misuse dynamic memory – writing
outside allocated bounds, using memory after freeing it, or freeing
something twice. These bugs can manifest as mysterious crashes, data
corruption, or program aborts deep inside <code class="language-plaintext highlighter-rouge">malloc()</code>/<code class="language-plaintext highlighter-rouge">free()</code>. Let’s
illustrate with a use-after-free scenario (a common heap corruption):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// heap_corruption.cpp
#include &lt;iostream&gt;
#include &lt;cstring&gt;
int main() {
    char* data = (char*)malloc(16);
    strcpy(data, "Hello");
    free(data);
    // Bug: use-after-free - writing to freed heap memory
    data[0] = 'h';                    // Writing to freed memory (heap corruption)
    std::cout &lt;&lt; data &lt;&lt; std::endl;   // Reading freed memory
    return 0;
}
</code></pre></div></div>

<p><strong>Symptoms:</strong> Running this program <em>without</em> any tools might still print
“hello” (if the memory wasn’t yet reused), or it might crash
unpredictably later. On Linux, a double free would often cause an
immediate abort with a message like “*** Error in <code class="language-plaintext highlighter-rouge">a.out</code>: double
free or corruption” printed to stderr. On Windows, a double free or heap
misuse might trigger a debug error or an access violation inside
<code class="language-plaintext highlighter-rouge">HeapFree</code>. These vague symptoms don’t directly pinpoint the bug.</p>

<p><strong>Using AddressSanitizer:</strong> To catch heap issues early, compile with
ASan enabled. For example, on Clang or GCC use <code class="language-plaintext highlighter-rouge">-fsanitize=address -g</code>
(and on MSVC use <code class="language-plaintext highlighter-rouge">/fsanitize=address</code> with Visual Studio 2019 or
later<a href="https://learn.microsoft.com/en-us/cpp/sanitizers/error-heap-buffer-overflow?view=msvc-170#:~:text=To%20build%20and%20test%20this,or%20later%20developer%20command%20prompt">[1]</a>).</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ clang++ -fsanitize=address -g heap_corruption.cpp -o heap_corruption
$ ./heap_corruption
=================================================================
==244157==ERROR: AddressSanitizer: heap-use-after-free on address 0x60b0000000f0 at pc 0x00000047a560 bp 0x7ffcdf0d59f0 sp 0x7ffcdf0d51a0
WRITE of size 1 at 0x60b0000000f0 thread T0
    #0 0x47a55f in __interceptor_memcpy ... sanitizer_common_interceptors.inc:790
    #1 0x528403 in main heap_corruption.cpp:8[2]
</code></pre></div></div>

<p>ASan immediately halts at the invalid access and prints a detailed
error. The message <strong>“heap-use-after-free”</strong> tells us we wrote to memory
after freeing it. The output shows a stack trace: frame <code class="language-plaintext highlighter-rouge">#1</code> points at
line 8 in our code (the <code class="language-plaintext highlighter-rouge">data[0] = 'h'</code>
write)<a href="https://www.osc.edu/resources/getting_started/howto/howto_use_address_sanitizer#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20%3D%3D244157%3D%3DERROR%3A%20AddressSanitizer%3A%20heap,c%3A8">[2]</a>.
It even shows the allocation and free history (not shown above for
brevity). <strong>This is a huge help:</strong> we now know exactly what went wrong
and where.</p>

<p>Next, let’s use a debugger to inspect the state at the moment of
failure:</p>

<ul>
  <li><strong>LLDB (macOS):</strong> We can run the ASan-instrumented program under LLDB.
Because ASan raises a signal when it detects the error, LLDB will
break at the point of failure. For example:</li>
</ul>

<!-- -->

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ lldb ./heap_corruption
(lldb) run
...
AddressSanitizer: heap-use-after-free ... (reports error)
(lldb) bt  # backtrace
</code></pre></div></div>

<p>The backtrace (<code class="language-plaintext highlighter-rouge">bt</code>) in LLDB will show our code frames, confirming the
crash at the <code class="language-plaintext highlighter-rouge">data[0] = 'h'</code> line. We can also inspect variables or
memory if needed. In this simple case, ASan already told us the cause,
but the debugger lets us verify program state (e.g., check that <code class="language-plaintext highlighter-rouge">data</code>
pointer value is the same freed address ASan reported).</p>

<ul>
  <li><strong>WinDbg (Windows):</strong> On Windows, you can achieve similar insight
using the <strong>Page Heap</strong> feature. By enabling <em>Page Heap</em> for your app
(using the <strong>GFlags</strong> tool), every heap allocation will be surrounded
by guard
pages<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug#:~:text=Step%201%3A%20Enable%20standard%20page,heap%20verification">[3]</a><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20VERIFIER%20STOP%2000000008%3A%20pid,0xAA0%3A%20corrupted%20suffix%20pattern">[4]</a>.
This means any out-of-bounds or use-after-free access triggers an
immediate access violation. For example, run:</li>
</ul>

<!-- -->

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>C:\&gt; gflags /p /enable heap_corruption.exe /full
C:\&gt; windbg heap_corruption.exe
</code></pre></div></div>

<p>When the use-after-free write occurs, WinDbg breaks execution on the
exact instruction. In full Page Heap mode, WinDbg might show a
<strong>“VERIFIER STOP 00000008: corrupted suffix pattern”</strong>
message<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20VERIFIER%20STOP%2000000008%3A%20pid,0xAA0%3A%20corrupted%20suffix%20pattern">[4]</a>
– indicating a buffer overflow or use-after-free was caught by the heap
verifier. You can then use WinDbg commands like <code class="language-plaintext highlighter-rouge">kb</code> (stack backtrace)
to see that the crash happened in our <code class="language-plaintext highlighter-rouge">main</code> at the offending line. The
<strong>heap verifier</strong> message “corrupted suffix pattern” specifically means
we wrote past the end of an allocated
block<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug#:~:text=The%20header%20information%20includes%20the,00000100%20%3A%20Block%20size">[5]</a>,
which matches our use-after-free (the freed block’s red-zone was
overwritten).</p>

<ul>
  <li><strong>VS Code + Debuggers:</strong> If you prefer a GUI, VS Code’s debug
environment can be used on both platforms. On macOS, use the CodeLLDB
extension to launch the program with ASan; it will break on the error
just like LLDB. On Windows, using the C++ (cppdbg) configuration, you
can launch under the Visual Studio debugger – the program will hit a
fault when the heap corruption is detected (either by ASan or Page
Heap). In VS Code, you’ll see the exception notification, and you can
open the <em>Call Stack</em> pane to find our code line. Essentially, VS Code
with these extensions provides a front-end to LLDB or the MSVC
debugger, so the information you get is similar.</li>
</ul>

<p><strong>Diagnostic reasoning:</strong> The key steps for a heap corruption bug are:</p>

<ol>
  <li>
    <p><strong>Reproduce with diagnostics enabled:</strong> Turn on ASan (or Page Heap)
to catch the violation as soon as it happens, rather than hunting
down downstream
effects<a href="https://www.osc.edu/resources/getting_started/howto/howto_use_address_sanitizer#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20%3D%3D244157%3D%3DERROR%3A%20AddressSanitizer%3A%20heap,c%3A8">[2]</a>.
This gives a clear starting point (the exact bad memory access).</p>
  </li>
  <li>
    <p><strong>Inspect the context:</strong> Use the debugger’s backtrace and variables
to confirm what’s being corrupted. In our case, we see the write to
a freed pointer. We’d inspect <code class="language-plaintext highlighter-rouge">data</code> to confirm it’s the same
address that was freed. A quick mental check or debugger inquiry
(“was this pointer freed already?”) confirms the bug.</p>
  </li>
  <li>
    <p><strong>Additional tools:</strong> If ASan hadn’t been used, we might have only a
crash in <code class="language-plaintext highlighter-rouge">free()</code> or an OS exception. In such a case, advanced heap
debugging commands help. For example, WinDbg’s <code class="language-plaintext highlighter-rouge">!heap</code> extension can
detect heap corruptions. After a crash, running
<code class="language-plaintext highlighter-rouge">!heap -p -a &lt;address&gt;</code> on the address in question can sometimes
show heap block status and that it was freed. But these are advanced
steps – using sanitizers is often the faster path for memory
errors.</p>
  </li>
  <li>
    <p><strong>Fix and retest:</strong> After identifying the misuse (e.g., remove the
stray <code class="language-plaintext highlighter-rouge">data[0]</code> write or ensure it happens before <code class="language-plaintext highlighter-rouge">free</code>), run again
with ASan to confirm the error is gone.</p>
  </li>
</ol>

<p><em>Side note:</em> Double-frees are another heap corruption. ASan catches
those too, typically with an error <strong>“attempting double-free”</strong> pointing
to the second <code class="language-plaintext highlighter-rouge">free</code>. On Windows, enabling Application Verifier (or Page
Heap full) will break on a double-free as well. Always pay attention to
these tool reports – they precisely flag heap misuse that might
otherwise be heisenbugs.</p>

<h2 id="2-buffer-overflow-case-study">2. Buffer Overflow Case Study</h2>

<p>Buffer overflows are a classic C/C++ bug: writing outside the bounds of
an array. They can smash the stack or heap, leading to corrupted data or
security vulnerabilities. Let’s consider a simple stack buffer overflow:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// buffer_overflow.cpp
#include &lt;iostream&gt;
#include &lt;cstring&gt;
int main() {
    char small[8];
    strcpy(small, "Overflow!");  // 9 characters into an 8-byte array (overflow)
    std::cout &lt;&lt; "small = " &lt;&lt; small &lt;&lt; std::endl;
}
</code></pre></div></div>

<p>Here, <code class="language-plaintext highlighter-rouge">small</code> has space for 7 characters + null terminator, but
“Overflow!” is 9 characters plus null. We overflow the stack buffer.
What happens? On many systems, this will overwrite the stack canary (a
guard value) and trigger a runtime check failure. For instance, on Linux
with default protections, you might see: <strong>“</strong> <em>stack smashing detected</em>
<strong>: terminated”</strong> and the program aborts. Without canary protection, it
might just corrupt adjacent data or the return address, causing bizarre
crashes.</p>

<p><strong>Using AddressSanitizer:</strong> Again, ASan is extremely useful. Compile
with ASan and run:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ clang++ -fsanitize=address -g buffer_overflow.cpp -o buffer_overflow
$ ./buffer_overflow
=================================================================
==1==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffe6acc8e70 at pc 0x5591ad37f523 bp 0x7ffe6acc8e68 sp 0x7ffe6acc8e60
READ of size 1 at 0x7ffe6acc8e70 thread T0
    #0 0x5591ad37f522 in main buffer_overflow.cpp:5:45
    #1 0x5591ad37f59a in main buffer_overflow.cpp:10:4
...[6]
</code></pre></div></div>

<p>ASan reports a <strong>“stack-buffer-overflow”</strong> (in this case it labels it
heap-buffer-overflow because <code class="language-plaintext highlighter-rouge">strcpy</code> tries to read beyond the allocated
chunk – but the key is the <strong>stack</strong> address in the error and the line
number). The stack trace shows the error originates at the <code class="language-plaintext highlighter-rouge">strcpy</code> call
in
<code class="language-plaintext highlighter-rouge">main</code><a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20%3D%3D1%3D%3DERROR%3A%20AddressSanitizer%3A%20heap,gnu%2Flibc.so.6%2B0x29d8f%29%20%28BuildId">[6]</a>.
ASan also typically explains where the overflow happened relative to the
buffer (e.g., “0 bytes to the right of 8-byte region”). This pinpoints
our mistake.</p>

<p><strong>Debugging the overflow:</strong></p>

<ul>
  <li>
    <p><strong>LLDB/VSCode (macOS):</strong> Under LLDB, a stack overflow that triggers
the canary will usually raise a SIGABRT. If you run the program in
LLDB, it will break at the abort signal. By examining the backtrace
(<code class="language-plaintext highlighter-rouge">bt</code>), you see the program died during or right after <code class="language-plaintext highlighter-rouge">strcpy</code>. You
can inspect the memory around <code class="language-plaintext highlighter-rouge">small</code> using LLDB’s memory commands
(e.g., <code class="language-plaintext highlighter-rouge">x/16bx &amp;small</code> to view bytes) to see that the string wasn’t
fully contained. With ASan, it breaks exactly at the point of
overflow, so the process is similar to the heap case: read ASan’s
output and confirm in debugger if needed.</p>
  </li>
  <li>
    <p><strong>WinDbg (Windows):</strong> In Visual C++ with security cookies (/GS), an
overflow will trigger an exception on function return. Under WinDbg or
VS, you’d see an access violation or an assert from the runtime. If
you suspect an overflow, you can use WinDbg’s <code class="language-plaintext highlighter-rouge">k</code> command to get a
call stack at the point of failure. It often shows the failure
occurred as <code class="language-plaintext highlighter-rouge">main</code> was returning (since the cookie check failed at end
of scope). Alternatively, compile with <code class="language-plaintext highlighter-rouge">/fsanitize=address</code> in MSVC
(available in VS2019+ as mentioned) to catch it instantly. The MSVC
AddressSanitizer will output a similar message in the debugger console
for the buffer
overflow<a href="https://learn.microsoft.com/en-us/cpp/sanitizers/error-heap-buffer-overflow?view=msvc-170#:~:text=To%20build%20and%20test%20this,or%20later%20developer%20command%20prompt">[1]</a>.</p>
  </li>
  <li>
    <p><strong>Page Heap is for heap only:</strong> Note that Page Heap doesn’t help for
stack overflows, since those happen in stack memory. Instead, on
Windows, one might use Visual Studio’s <code class="language-plaintext highlighter-rouge">/RTC</code> runtime checks or the
sanitizer as discussed.</p>
  </li>
</ul>

<p><strong>Takeaway:</strong> The strategy for buffer overflows is to <strong>catch them where
they occur</strong>. ASan’s report gave us the file and line, so we know the
fix is to correct the <code class="language-plaintext highlighter-rouge">strcpy</code> (or better, use <code class="language-plaintext highlighter-rouge">strncpy</code> with correct
length, or increase the buffer). In more complex cases (e.g., buffer
overflow in a large input), you might set a breakpoint at a suspicious
loop and watch indices or use debugger watchpoints on array boundaries.
For example, if you have an array <code class="language-plaintext highlighter-rouge">arr[N]</code>, you can set a watchpoint on
<code class="language-plaintext highlighter-rouge">arr[N]</code> (the first byte past the end) to break when it’s written. In
LLDB:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) watchpoint set expression -w write -- (&amp;arr[N])
</code></pre></div></div>

<p>This will halt when code writes beyond the valid range. In WinDbg, you
can do similarly with a data breakpoint (if you know the address). But
frankly, using a sanitizer or adding manual bounds checks is easier and
safer for catching overflows.</p>

<h2 id="3-memory-alignment-issues">3. Memory Alignment Issues</h2>

<p>Not all bugs crash immediately – some just cause <em>weird behavior or
slowdowns</em>. One example is misaligned memory access. On many
architectures (ARM, for instance), reading a 4-byte integer from a
non-4-byte-aligned address can trigger a hardware fault or a performance
penalty. Consider this code:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// alignment.cpp
#include &lt;iostream&gt;
#include &lt;cstdint&gt;
int main() {
    alignas(1) struct Misalign { char c; int x; }; 
    Misalign m;
    char* ptr = reinterpret_cast&lt;char*&gt;(&amp;m);
    // Intentionally misalign an int pointer by 1:
    int* misInt = reinterpret_cast&lt;int*&gt;(ptr + 1);
    *misInt = 42;  // write to an int at an unaligned address
    std::cout &lt;&lt; "misInt=" &lt;&lt; *misInt &lt;&lt; std::endl;
}
</code></pre></div></div>

<p>We force an <code class="language-plaintext highlighter-rouge">int</code> to be at an odd address (<code class="language-plaintext highlighter-rouge">ptr+1</code>). On x86, this
<strong>won’t crash</strong> – x86 can handle unaligned access (just slower). But on
stricter architectures (say, some ARM or SPARC systems), that line would
crash with a bus error. How can we debug something that doesn’t
obviously crash on our machine? <strong>UndefinedBehaviorSanitizer (UBSan)</strong>
to the rescue.</p>

<p>Compile with UBSan enabled: <code class="language-plaintext highlighter-rouge">-fsanitize=undefined -g</code>. Running this on
x86 might produce:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>runtime error: store to misaligned address 0x7ffdba454351 for type 'uint16_t' (aka 'unsigned short'), which requires 2 byte alignment[7]  
0x7ffdba454351: note: pointer points here ...  
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior alignment.cpp:12:5
</code></pre></div></div>

<p>UBSan caught the misaligned access and printed a runtime error. (In our
example, it might mention <code class="language-plaintext highlighter-rouge">uint16_t</code> if our types differ, but the idea
is the same – it will complain that an address isn’t properly aligned
for the target
type<a href="https://github.com/iree-org/iree/issues/16608#:~:text=%5B%20RUN%20%5D%20MemoryStreamTest.Fill%20%2Fopt%2Fwork%2Firee%2Fgithub,behavior%20%2Fopt%2Fwork%2Firee%2Fgithub">[7]</a>.)
The output also identifies the exact line in <code class="language-plaintext highlighter-rouge">alignment.cpp</code> where the
issue occurs.</p>

<p><strong>Using the debugger:</strong> If you run this under LLDB on a system where it
doesn’t crash, you won’t get an automatic break – the program might
happily print a value (potentially the wrong value if the hardware did
multiple accesses). In such cases, using UBSan is the best first step
because it flags an issue that the debugger wouldn’t notice on its own
(since the program didn’t crash). Once UBSan points it out, you use the
source info to fix the code (in this case, ensure proper alignment or
avoid such pointer casts).</p>

<p>If you <em>were</em> on a system where it crashed (say an ARM device or an
emulator that faults on misalignment), then the debugger would catch a
SIGBUS or similar. The backtrace would show the faulting instruction at
the <code class="language-plaintext highlighter-rouge">*misInt = 42</code> line. You could then examine the pointer value and
realize it’s not divisible by 4, indicating misalignment.</p>

<p><strong>Diagnostic mindset:</strong> Memory alignment bugs often hide as performance
issues or platform-specific crashes. The senior approach is to use UBSan
instrumentation proactively to detect undefined behaviors like this. As
the Clang documentation shows, UBSan can catch misaligned pointer use,
null dereferences, integer overflows, and
more<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,bounds%20can%20be%20statically%20determined">[8]</a><a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,be%20represented%20in%20type%20%27int">[9]</a>.
The sanitizer is essentially your early warning system. Once a runtime
error is reported, you can use a debugger to inspect how that misaligned
address came to be (e.g. inspect the struct layout or pointer arithmetic
leading to it). In our example, seeing <code class="language-plaintext highlighter-rouge">ptr+1</code> in code is an obvious
bug, but in bigger codebases you might binary search with breakpoints or
print addresses to locate where the misalignment originates.</p>

<h2 id="4-nasty-undefined-behavior-cases-odr-violations--integer-overflow">4. Nasty Undefined Behavior Cases (ODR Violations &amp; Integer Overflow)</h2>

<p>Undefined behavior (UB) in C++ can lead to <em>astonishingly weird</em> bugs
because the program’s behavior is literally unpredictable by the
standard. Two advanced examples are: One-Definition Rule (ODR)
violations and signed integer overflow.</p>

<ul>
  <li><strong>ODR Violation Scenario:</strong> Imagine you have a header defining a
struct or class, but two source files include slightly different
versions (perhaps a compile-time macro causes the size to differ).
This violates the ODR – the program is ill-formed, but it might still
compile and run… albeit incorrectly. You might see memory corruption
(as one translation unit expects an object of one size while another
writes beyond it). These are extremely hard to debug by guesswork.
Tools can help: AddressSanitizer can detect some ODR violations at
program startup (with a special flag) by comparing type
metadata<a href="https://github.com/google/sanitizers/wiki/AddressSanitizerOneDefinitionRuleViolation#:~:text=AddressSanitizer%2C%20however%2C%20is%20able%20to,time%20switch">[10]</a>.
UBSan also has checks for ODR violations. If enabled, it might print a
runtime error when it detects two definitions of the same entity that
don’t match. For example, if class <code class="language-plaintext highlighter-rouge">Foo</code> is defined differently in two
.cpp files, UBSan could report an error at runtime like <em>“ODR
violation: Foo has different size in module A and B”</em>.</li>
</ul>

<p><strong>Debugging approach:</strong> If you suspect an ODR issue (e.g., weird
behavior only when certain object files are linked together), enabling
UBSan’s ODR checker is step one. Once it flags something, you’ve
basically found the culprit (you’ll need to reconcile the definitions in
your code). In a debugger, there’s not a specific “ODR command,” but a
clever trick is to compare <code class="language-plaintext highlighter-rouge">sizeof(Foo)</code> in different compilation units
if you can. For instance, in WinDbg or LLDB you could evaluate type
sizes or inspect object memory layouts to see a mismatch. This is
advanced (and usually not necessary thanks to sanitizers). The main
point: trust the sanitizer and then double-check your code for multiple
definitions.</p>

<ul>
  <li><strong>Signed Integer Overflow:</strong> By C++ rules, overflowing a signed
integer (e.g., doing <code class="language-plaintext highlighter-rouge">INT_MAX + 1</code>) is undefined behavior. On typical
hardware it will wrap around, but the compiler might assume it never
happens and optimize accordingly, leading to logic bugs. Let’s say we
have:</li>
</ul>

<!-- -->

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>int a = INT32_MAX;
int b = a + 1;  // UB: signed overflow
printf("b = %d\n", b);
</code></pre></div></div>

<p>Most likely, <code class="language-plaintext highlighter-rouge">b</code> will end up as <code class="language-plaintext highlighter-rouge">-2147483648</code> due to two’s complement
wraparound. The program might appear to work, but imagine if this
overflow is controlling a loop or array index – it could cause wrong
results or buffer access on the wrong side of an array. <strong>UBSan</strong>
catches this too. If compiled with <code class="language-plaintext highlighter-rouge">-fsanitize=undefined</code>, running might
print a message:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'[11].
</code></pre></div></div>

<p>This tells us an overflow happened at that line. In a debugger, such an
overflow won’t raise an exception (the CPU just wraps around), so it’s
hard to notice. The senior approach upon suspecting overflow is to add
instrumentation or checks. With UBSan flagging it, we know to fix the
code (perhaps use larger types or check for overflow before adding).</p>

<p>If we didn’t have UBSan, one could manually watch the value in the
debugger. For example, set a breakpoint at the addition and check the
values of <code class="language-plaintext highlighter-rouge">a</code> and <code class="language-plaintext highlighter-rouge">b</code>. Tools like LLDB support conditional breakpoints
– e.g., break when <code class="language-plaintext highlighter-rouge">a</code> is near INT_MAX. But this requires you to
<em>suspect</em> the overflow in advance. That’s why using sanitizers during
testing is invaluable for catching these invisible errors.</p>

<p><strong>Summary of UB debugging:</strong> Use UBSan to <strong>detect</strong> subtle undefined
behaviors (alignment, overflows, null deref, etc.) at runtime with
informative
messages<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,be%20represented%20in%20type%20%27int">[9]</a>.
Once detected, use the debugger to further examine state if needed.
Often, the fix is straightforward once you know what happened (e.g.,
avoid relying on overflow, fix inconsistent definitions, etc.). The
combination of UBSan’s diagnostics with a debugger’s ability to inspect
program state gives you both the “what happened” and the “how we got
here.”</p>

<h2 id="5-multithreading-bugs-race-conditions-data-corruption-and-deadlocks">5. Multithreading Bugs: Race Conditions, Data Corruption, and Deadlocks</h2>

<p>Concurrency bugs are some of the trickiest to reproduce and debug. They
might only show up under specific timing, making them <strong>heisenbugs</strong>
(the act of debugging can change the timing and hide the bug!). We’ll
look at two common classes: data races (leading to corrupted data) and
deadlocks.</p>

<h3 id="race-conditions-and-data-corruption">Race Conditions and Data Corruption</h3>

<p>A <strong>race condition</strong> occurs when two or more threads access the same
data without proper synchronization, and at least one is a write. The
outcome can vary run-to-run, with incorrect results or corrupted state.
Consider:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// race.cpp
#include &lt;thread&gt;
#include &lt;iostream&gt;
static int counter = 0;
void incr() {
    for(int i = 0; i &lt; 1000000; ++i) {
        counter++;  // data race on counter
    }
}
int main() {
    std::thread t1(incr);
    std::thread t2(incr);
    t1.join();
    t2.join();
    std::cout &lt;&lt; "Final counter = " &lt;&lt; counter &lt;&lt; std::endl;
}
</code></pre></div></div>

<p>We forgot to protect <code class="language-plaintext highlighter-rouge">counter</code> with a mutex or atomic. The two threads
race to update it. If you run this, <strong>sometimes</strong> you’ll get the correct
<code class="language-plaintext highlighter-rouge">2000000</code>, but often you’ll get a smaller number (lost increments) due
to overlapped operations. There’s no crash – just wrong output.</p>

<p><strong>Diagnosing races:</strong> Traditional debuggers don’t automatically flag
data races. Here’s how to tackle it:</p>

<ul>
  <li>
    <p><strong>ThreadSanitizer (TSan):</strong> Although not asked in the prompt, it’s
worth mentioning: TSan is the sanitizer for data races. If you compile
with <code class="language-plaintext highlighter-rouge">-fsanitize=thread</code>, running the program would spew a report the
moment a data race is detected, showing the two threads’ code paths
that conflicted. For example, TSan might say “Data race on <code class="language-plaintext highlighter-rouge">counter</code>
in function incr() ...” with stack traces for both threads. This is
immensely helpful – it tells you which variable and where the
unsynchronized access occurred. (TSan reports look somewhat like
ASan’s, describing the memory address and threads; if you ever suspect
a race, this tool is a go-to.)</p>
  </li>
  <li>
    <p><strong>Logging &amp; Debugger Tricks:</strong> Without TSan, you can insert logging:
e.g., have each thread print when it updates <code class="language-plaintext highlighter-rouge">counter</code>. This will
likely intermix output and show you that they are running
concurrently. But logging can slow things and alter timing.</p>
  </li>
  <li>
    <p><strong>Watchpoints (Data Breakpoints):</strong> A powerful debugger feature for
data corruption is the <strong>watchpoint</strong> (also called data breakpoint).
This lets you break execution when a specific memory location is
accessed or changed. For instance, suppose <code class="language-plaintext highlighter-rouge">counter</code> was getting
mysteriously set to a wrong value by some race or stray pointer. In
LLDB you can do:</p>
  </li>
</ul>

<!-- -->

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) watchpoint set variable -w write counter
</code></pre></div></div>

<p>This tells LLDB to pause whenever <code class="language-plaintext highlighter-rouge">counter</code> is
written<a href="https://gist.github.com/rais38/6ecead686af9291da542#:~:text=Set%20a%20watchpoint%20on%20a,option%20terminator">[12]</a>.
In GDB, the analogous command is <code class="language-plaintext highlighter-rouge">watch counter</code>. In WinDbg, you’d use
the <code class="language-plaintext highlighter-rouge">ba</code> (break on access) command (e.g., <code class="language-plaintext highlighter-rouge">ba w 4 &amp;counter</code> to watch 4
bytes at counter’s address). In VS Code, modern versions allow data
breakpoints too – if you’re stopped in debug, you can right-click a
variable in the <em>Watch</em> window and select “Break when value
changes”<a href="https://devblogs.microsoft.com/cppblog/data-breakpoints-15-8-update/#:~:text=Now%2C%20data%20breakpoints%20can%20also,up%20notification%20about%20the%20change">[13]</a>.
Once set, <strong>resume execution</strong>. The program will run and whenever <em>any
thread</em> modifies that variable, the debugger will pause and show you the
context.</p>

<p>How does this help with our <code class="language-plaintext highlighter-rouge">counter</code>? If we set a watchpoint on
<code class="language-plaintext highlighter-rouge">counter</code> and run the race program, the debugger will break on the first
modification. That’s not super useful if we break on every increment
(we’d stop a million times!). But you can refine the strategy: for
example, set a condition to break only when <code class="language-plaintext highlighter-rouge">counter</code> becomes a specific
unexpected value or exceeds a threshold. Some debuggers allow
conditional watchpoints; in LLDB you could do
<code class="language-plaintext highlighter-rouge">watchpoint modify -c "counter &gt; 100 &amp;&amp; counter &lt; 1000"</code> as a contrived
example. Or simply let it run and break at some random increment – then
use the debugger’s thread view to see what both threads are doing. If
you see two threads in <code class="language-plaintext highlighter-rouge">counter++</code> concurrently, you’ve confirmed the
race.</p>

<p>Another scenario: <strong>memory corruption from races</strong> – suppose a data
structure gets corrupted occasionally. A senior debugger move is to
watch the memory address that keeps getting corrupted. When the
watchpoint fires, it reveals <em>which code</em> did the write. For instance,
if an integer turns to an unexpected value “42” and you suspect a race,
set a watchpoint. When it triggers, the call stack will show the culprit
thread and function that wrote to it, solving the mystery of “who the
hell writes 2 into my variable” (as one famous debugging story
goes)<a href="https://khorbushko.github.io/article/2021/05/27/the-lldb-debugger-part3-watchpoint.html#:~:text=Often%2C%20,some%20cases%2C%20but%2C%20not%20always">[14]</a>.
Watchpoints are gold for catching intermittent data corruption by
breaking at the exact moment of change.</p>

<ul>
  <li><strong>Stepping and breakpoints:</strong> You might attempt to step through both
threads interleaved by setting breakpoints and using debugger controls
to switch threads. This is cumbersome and not usually effective unless
you <em>already</em> know where to look. Instead, a better mindset is to
narrow down the race to a region of code (we know <code class="language-plaintext highlighter-rouge">counter++</code> is the
spot here) and use tools or instrumentation to catch it.</li>
</ul>

<p>In our <code class="language-plaintext highlighter-rouge">counter</code> example, the fix is to guard the increment with a mutex
or make <code class="language-plaintext highlighter-rouge">counter</code> an <code class="language-plaintext highlighter-rouge">std::atomic&lt;int&gt;</code>. But witnessing the
non-deterministic outcome (final values varying) or using
TSan/watchpoints to catch concurrent access gives you confidence about
the root cause.</p>

<h3 id="deadlocks">Deadlocks</h3>

<p>A deadlock happens when two or more threads lock resources in an
inconsistent order, causing each to wait forever for the other. The
program just hangs – no crash, no error message. Let’s simulate a
deadlock:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// deadlock.cpp
#include &lt;mutex&gt;
#include &lt;thread&gt;
int main() {
    std::mutex m1, m2;
    auto task1 = [&amp;]() {
        std::lock_guard&lt;std::mutex&gt; lock1(m1);
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        std::lock_guard&lt;std::mutex&gt; lock2(m2);
    };
    auto task2 = [&amp;]() {
        std::lock_guard&lt;std::mutex&gt; lock2(m2);
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        std::lock_guard&lt;std::mutex&gt; lock1(m1);
    };
    std::thread t1(task1);
    std::thread t2(task2);
    t1.join(); t2.join();
}
</code></pre></div></div>

<p>Thread 1 locks m1 then m2, while Thread 2 locks m2 then m1. The 100ms
sleep ensures they each get the first lock and then try for the second,
leading to a deadlock. The program will hang at join and never
terminate.</p>

<p><strong>Diagnosing a deadlock:</strong> When your program seems stuck, a common
approach is to pause it in a debugger and examine thread states:</p>

<ul>
  <li>
    <p><strong>Visual Debuggers (VS, VS Code):</strong> If you attach to or launch the
hung program in VS Code or Visual Studio, you can hit the “pause”
button (break all). The debugger will halt all threads wherever they
are. Then open the <em>Threads</em> panel. You’ll likely see one thread’s
call stack stopped in <code class="language-plaintext highlighter-rouge">lock_guard</code> (inside <code class="language-plaintext highlighter-rouge">pthread_mutex_lock</code> on
Unix or <code class="language-plaintext highlighter-rouge">EnterCriticalSection</code> on Windows), and the other thread
similarly paused trying to acquire the other mutex. Each owns one lock
and waits on the other – classic deadlock. By looking at the call
stack, you see exactly which line in <code class="language-plaintext highlighter-rouge">task1</code> and <code class="language-plaintext highlighter-rouge">task2</code> they’re
waiting at. This tells you the locks are acquired in inconsistent
order.</p>
  </li>
  <li>
    <p><strong>LLDB (CLI):</strong> In LLDB, you can do <code class="language-plaintext highlighter-rouge">thread list</code> to see all threads,
then <code class="language-plaintext highlighter-rouge">thread backtrace all</code> (or the shorthand <code class="language-plaintext highlighter-rouge">bt all</code>). This will
print the backtrace of each thread. You would see something like:
Thread 1’s trace includes <code class="language-plaintext highlighter-rouge">lock_guard&lt;std::mutex&gt; lock1(m1)</code> and is
now inside the mutex code waiting for m2, and Thread 2’s trace
includes <code class="language-plaintext highlighter-rouge">lock_guard&lt;std::mutex&gt; lock2(m2)</code> now waiting for m1. LLDB
doesn’t have a special deadlock detector, but this manual inspection
reveals it. There’s no “deadlock exception” – the program is just
waiting, so you use the debugger’s ability to snapshot all threads.</p>
  </li>
  <li>
    <p><strong>WinDbg:</strong> In WinDbg, you can break into the hung process (Debug -&gt;
Break). Use <code class="language-plaintext highlighter-rouge">~*kp</code> to get all thread stacks. You’ll see one thread in
something like <code class="language-plaintext highlighter-rouge">ntdll!ZwWaitForSingleObject</code> or
<code class="language-plaintext highlighter-rouge">KernelBase!WaitForCriticalSection</code> (if it’s a CriticalSection), and
the other thread in a similar wait. WinDbg has an extension <code class="language-plaintext highlighter-rouge">!locks</code>
which can list owned critical sections and who owns
them<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/displaying-a-critical-section#:~:text=0%3A000">[15]</a>.
If our std::mutex uses Win32 CriticalSections under the hood, running
<code class="language-plaintext highlighter-rouge">!locks</code> might output each lock, showing one is owned by thread X and
one by thread Y, each with one waiting thread. For example, <code class="language-plaintext highlighter-rouge">!locks</code>
output might show “CritSec m1 … OwningThread = thread1id,
LockCount=1, EntryCount=1” and “CritSec m2 … OwningThread =
thread2id, LockCount=1…”. That confirms the deadlock circle. (Note:
<code class="language-plaintext highlighter-rouge">!locks</code> requires symbols and works for known synchronization
primitives; it’s very useful in complex apps to list all locks and
owners<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/displaying-a-critical-section#:~:text=0%3A000">[15]</a>.)</p>
  </li>
</ul>

<p><strong>Resolving deadlocks:</strong> The fix is to enforce a consistent locking
order or use lock ordering utilities (like <code class="language-plaintext highlighter-rouge">std::scoped_lock(m1, m2)</code>
which locks both in a defined order). But from a debugging perspective,
the “Aha!” moment is realizing threads are stuck waiting on each other.
The debugger gives you that insight by frozen call stacks. A senior dev
also knows to <strong>suspect deadlock</strong> if an app is unresponsive and
especially if the threads involved hold locks – then immediately go to
thread dump analysis as above.</p>

<p><strong>Tip:</strong> Sometimes deadlocks only happen under certain conditions. If
you can’t reproduce easily, you might force-break the program when it
hangs (e.g., sending a SIGINT to generate a core dump, or on Windows
using Task Manager to create a dump file). Then you can load that dump
in WinDbg or LLDB and perform the same thread stack inspection. It’s
post-mortem debugging, but the thread traces will often show the
circular wait.</p>

<hr />

<h2 id="conclusion">Conclusion</h2>

<p>Debugging advanced C++ bugs requires a blend of the right tools and the
right mindset. We covered how <strong>sanitizers</strong> like ASan and UBSan act as
bug radar – catching memory errors and undefined behavior <em>as soon as
they happen</em>, with helpful diagnostics. We saw how to compile and
interpret their reports, using them to zero in on the offending code
lines (for example, ASan pointing out a heap buffer
overflow<a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20%3D%3D1%3D%3DERROR%3A%20AddressSanitizer%3A%20heap,gnu%2Flibc.so.6%2B0x29d8f%29%20%28BuildId">[6]</a>
or UBSan alerting us to an integer
overflow<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=%25%20clang%2B%2B%20,be%20represented%20in%20type%20%27int">[11]</a>).
We then paired that with systematic <strong>debugger workflows</strong>: setting
breakpoints/watchpoints, inspecting memory and threads, and using
platform-specific features (like Page Heap on
Windows<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20VERIFIER%20STOP%2000000008%3A%20pid,0xAA0%3A%20corrupted%20suffix%20pattern">[4]</a>
or LLDB’s watchpoints) to unravel the bug completely.</p>

<p>For each case – whether it’s a rogue memory write, an overflow, or a
multithreading blunder – the process was: <strong>observe symptoms, use tools
to trap the bug in action, then investigate state with a debugger to
understand and confirm the cause.</strong> By combining sanitizer output with
interactive debugging, we get both the high-level error report <em>and</em> the
low-level insight. This is the senior developer’s approach: <strong>leverage
every aid available</strong>, and methodically narrow down the problem.</p>

<p>As you tackle your own tough bugs, remember these examples. If something
“impossible” is happening, think of undefined behavior – and try UBSan.
If memory is mysteriously corrupt, run with ASan or set a watchpoint to
catch the culprit. If your app hangs, break in and examine thread
backtraces. By practicing these techniques, you’ll not only fix the bug
at hand but also build an intuition for debugging that will serve you
throughout your C++ career. Happy debugging!</p>

<p><strong>Sources:</strong> The techniques and outputs above were informed by sanitizer
documentation<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,be%20represented%20in%20type%20%27int">[9]</a><a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=%25%20clang%2B%2B%20,be%20represented%20in%20type%20%27int">[11]</a>,
official debugging guides, and real-world examples of using LLDB,
WinDbg, and VS Code. Notably, AddressSanitizer and
UndefinedBehaviorSanitizer are documented by Clang/LLVM and provide
clear error messages for issues like
heap-use-after-free<a href="https://www.osc.edu/resources/getting_started/howto/howto_use_address_sanitizer#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20%3D%3D244157%3D%3DERROR%3A%20AddressSanitizer%3A%20heap,c%3A8">[2]</a>
and misaligned memory
access<a href="https://github.com/iree-org/iree/issues/16608#:~:text=%5B%20RUN%20%5D%20MemoryStreamTest.Fill%20%2Fopt%2Fwork%2Firee%2Fgithub,behavior%20%2Fopt%2Fwork%2Firee%2Fgithub">[7]</a>.
Microsoft’s documentation on Page Heap and debugger extensions
illustrates how WinDbg catches heap corruption (e.g., “corrupted suffix
pattern” on
overflow)<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20VERIFIER%20STOP%2000000008%3A%20pid,0xAA0%3A%20corrupted%20suffix%20pattern">[4]</a>
and how Visual Studio/VS Code support data breakpoints for tracking down
errant
writes<a href="https://devblogs.microsoft.com/cppblog/data-breakpoints-15-8-update/#:~:text=Now%2C%20data%20breakpoints%20can%20also,up%20notification%20about%20the%20change">[13]</a><a href="https://learn.microsoft.com/en-us/shows/pure-virtual-cpp-2022/data-breakpoints-in-visual-studio-code#:~:text=Data%20breakpoints%20in%20GDB%20allow,be%20hard%20to%20track%20down">[16]</a>.
By applying these tools as shown, you can conquer even the most
perplexing C++ bugs.
<a href="https://www.osc.edu/resources/getting_started/howto/howto_use_address_sanitizer#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20%3D%3D244157%3D%3DERROR%3A%20AddressSanitizer%3A%20heap,c%3A8">[2]</a><a href="https://github.com/iree-org/iree/issues/16608#:~:text=%5B%20RUN%20%5D%20MemoryStreamTest.Fill%20%2Fopt%2Fwork%2Firee%2Fgithub,behavior%20%2Fopt%2Fwork%2Firee%2Fgithub">[7]</a><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20VERIFIER%20STOP%2000000008%3A%20pid,0xAA0%3A%20corrupted%20suffix%20pattern">[4]</a><a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=%25%20clang%2B%2B%20,be%20represented%20in%20type%20%27int">[11]</a></p>

<hr />

<p><a href="https://learn.microsoft.com/en-us/cpp/sanitizers/error-heap-buffer-overflow?view=msvc-170#:~:text=To%20build%20and%20test%20this,or%20later%20developer%20command%20prompt">[1]</a>
Error: heap-buffer-overflow | Microsoft Learn</p>

<p><a href="https://learn.microsoft.com/en-us/cpp/sanitizers/error-heap-buffer-overflow?view=msvc-170">https://learn.microsoft.com/en-us/cpp/sanitizers/error-heap-buffer-overflow?view=msvc-170</a></p>

<p><a href="https://www.osc.edu/resources/getting_started/howto/howto_use_address_sanitizer#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20%3D%3D244157%3D%3DERROR%3A%20AddressSanitizer%3A%20heap,c%3A8">[2]</a>
HOWTO: Use Address Sanitizer | Ohio Supercomputer Center</p>

<p><a href="https://www.osc.edu/resources/getting_started/howto/howto_use_address_sanitizer">https://www.osc.edu/resources/getting_started/howto/howto_use_address_sanitizer</a></p>

<p><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug#:~:text=Step%201%3A%20Enable%20standard%20page,heap%20verification">[3]</a>
<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20VERIFIER%20STOP%2000000008%3A%20pid,0xAA0%3A%20corrupted%20suffix%20pattern">[4]</a>
<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug#:~:text=The%20header%20information%20includes%20the,00000100%20%3A%20Block%20size">[5]</a>
Example 12 Using Page Heap Verification to Find a Bug - Windows drivers
| Microsoft Learn</p>

<p><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug">https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/example-12---using-page-heap-verification-to-find-a-bug</a></p>

<p><a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20%3D%3D1%3D%3DERROR%3A%20AddressSanitizer%3A%20heap,gnu%2Flibc.so.6%2B0x29d8f%29%20%28BuildId">[6]</a>
Understanding AddressSanitizer: Better memory safety for your code - The
Trail of Bits Blog</p>

<p><a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/">https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/</a></p>

<p><a href="https://github.com/iree-org/iree/issues/16608#:~:text=%5B%20RUN%20%5D%20MemoryStreamTest.Fill%20%2Fopt%2Fwork%2Firee%2Fgithub,behavior%20%2Fopt%2Fwork%2Firee%2Fgithub">[7]</a>
ubsan load/store misaligned address errors from memory_stream_test and
gguf_parser_test · Issue #16608 · iree-org/iree · GitHub</p>

<p><a href="https://github.com/iree-org/iree/issues/16608">https://github.com/iree-org/iree/issues/16608</a></p>

<p><a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,bounds%20can%20be%20statically%20determined">[8]</a>
<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,be%20represented%20in%20type%20%27int">[9]</a>
<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=%25%20clang%2B%2B%20,be%20represented%20in%20type%20%27int">[11]</a>
UndefinedBehaviorSanitizer — Clang 23.0.0git documentation</p>

<p><a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html">https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html</a></p>

<p><a href="https://github.com/google/sanitizers/wiki/AddressSanitizerOneDefinitionRuleViolation#:~:text=AddressSanitizer%2C%20however%2C%20is%20able%20to,time%20switch">[10]</a>
AddressSanitizerOneDefinitionR...</p>

<p><a href="https://github.com/google/sanitizers/wiki/AddressSanitizerOneDefinitionRuleViolation">https://github.com/google/sanitizers/wiki/AddressSanitizerOneDefinitionRuleViolation</a></p>

<p><a href="https://gist.github.com/rais38/6ecead686af9291da542#:~:text=Set%20a%20watchpoint%20on%20a,option%20terminator">[12]</a>
Watchpoint in LLDB · GitHub</p>

<p><a href="https://gist.github.com/rais38/6ecead686af9291da542">https://gist.github.com/rais38/6ecead686af9291da542</a></p>

<p><a href="https://devblogs.microsoft.com/cppblog/data-breakpoints-15-8-update/#:~:text=Now%2C%20data%20breakpoints%20can%20also,up%20notification%20about%20the%20change">[13]</a>
Data Breakpoints - Visual Studio 2017 15.8 Update   - C++ Team Blog</p>

<p><a href="https://devblogs.microsoft.com/cppblog/data-breakpoints-15-8-update/">https://devblogs.microsoft.com/cppblog/data-breakpoints-15-8-update/</a></p>

<p><a href="https://khorbushko.github.io/article/2021/05/27/the-lldb-debugger-part3-watchpoint.html#:~:text=Often%2C%20,some%20cases%2C%20but%2C%20not%20always">[14]</a>
The LLDB Debugger - Part 3: Watchpoint | kyryl horbushko</p>

<p><a href="https://khorbushko.github.io/article/2021/05/27/the-lldb-debugger-part3-watchpoint.html">https://khorbushko.github.io/article/2021/05/27/the-lldb-debugger-part3-watchpoint.html</a></p>

<p><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/displaying-a-critical-section#:~:text=0%3A000">[15]</a>
Displaying a Critical Section - Windows drivers | Microsoft Learn</p>

<p><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/displaying-a-critical-section">https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/displaying-a-critical-section</a></p>

<p><a href="https://learn.microsoft.com/en-us/shows/pure-virtual-cpp-2022/data-breakpoints-in-visual-studio-code#:~:text=Data%20breakpoints%20in%20GDB%20allow,be%20hard%20to%20track%20down">[16]</a>
Data Breakpoints in Visual Studio Code | Microsoft Learn</p>

<p><a href="https://learn.microsoft.com/en-us/shows/pure-virtual-cpp-2022/data-breakpoints-in-visual-studio-code">https://learn.microsoft.com/en-us/shows/pure-virtual-cpp-2022/data-breakpoints-in-visual-studio-code</a></p>]]></content><author><name>Colin Neilens</name></author><category term="cpp" /><category term="debugging" /><category term="advanced" /><summary type="html"><![CDATA[In this final installment of our C++ debugging series, we’ll dive into some truly gnarly bugs that even seasoned developers struggle with. We’ll tackle heap corruption, buffer overflows, memory alignment issues, sneaky undefined behavior (like ODR violations and integer overflow), and multithreading nightmares (race conditions, data corruption, deadlocks). For each case study, we’ll walk through the senior debugging mindset step-by-step. You’ll see how to use AddressSanitizer (ASan) and UndefinedBehaviorSanitizer (UBSan) to catch errors, and then leverage powerful debuggers – LLDB (macOS), WinDbg (Windows), VS Code + CodeLLDB (macOS), and VS Code + CppDbg (Windows) – to trace problems down to the root cause. Let’s get started!]]></summary></entry><entry><title type="html">Debugging Memory Corruption and Crashes in C++ (Part 3)</title><link href="https://kobolinsapps.com/2026/01/16/debugging-memory-corruption-part3/" rel="alternate" type="text/html" title="Debugging Memory Corruption and Crashes in C++ (Part 3)" /><published>2026-01-16T10:00:00+00:00</published><updated>2026-01-16T10:00:00+00:00</updated><id>https://kobolinsapps.com/2026/01/16/debugging-memory-corruption-part3</id><content type="html" xml:base="https://kobolinsapps.com/2026/01/16/debugging-memory-corruption-part3/"><![CDATA[<p>In this third part of our series, we’ll walk through <strong>multiple
debugging case studies</strong> involving memory corruption, crashes, and
undefined behavior in C++ programs. We’ll use <strong>the same buggy code in
each case</strong> and debug it step-by-step with four different
tools/environments:</p>

<ul>
  <li><strong>LLDB on macOS</strong> (command-line debugger)</li>
  <li><strong>WinDbg on Windows</strong> (Windows debugger, using MSVC symbols)</li>
  <li><strong>VS Code with CodeLLDB</strong> (on macOS)</li>
  <li><strong>VS Code with CppDbg</strong> (on Windows, using GDB)</li>
</ul>

<p>For each case study, we’ll present a <strong>realistic code example</strong> (null
pointer dereference, use-after-free, stack overflow, race condition,
etc.) and then do a <strong>complete walkthrough</strong> of debugging that bug using
each tool. Along the way, we’ll highlight the <strong>senior engineer’s
thought process</strong>: how to compile with debug info, set breakpoints, run
the program under a debugger, interpret crashes or incorrect behavior,
inspect variables, examine call stacks and memory, use watchpoints (data
breakpoints), and ultimately identify the root cause of the bug. The
tone remains friendly and hands-on, guiding you through each step just
as in the earlier articles. Let’s dive in!</p>

<h2 id="case-study-1-null-pointer-dereference-crash-single-threaded">Case Study 1: Null Pointer Dereference Crash (Single-Threaded)</h2>

<p><strong>The Bug:</strong> Our first example is a classic <em>null pointer dereference</em>.
The program calls a function with a null pointer, and that function
tries to dereference it, leading to a crash. This is a simple scenario
to get started with debugging basics.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#include &lt;iostream&gt;

void foo(int* ptr) {
    // Attempt to write to the pointer
    *ptr = 42;  // BUG: ptr is null, this will crash
}

int main() {
    int *p = nullptr;
    foo(p);  // calling foo with a null pointer
    std::cout &lt;&lt; "This will not execute.\n";
    return 0;
}
</code></pre></div></div>

<p>If you compile and run this program normally, it will crash with a
<strong>segmentation fault</strong> (access violation) because we tried to write to
memory address 0 (null). The goal is to use each debugger to catch this
crash and confirm that the pointer was null.</p>

<h3 id="debugging-with-lldb-macos">Debugging with LLDB (macOS)</h3>

<p><strong>Step 1: Compile with debug symbols.</strong> On macOS, we’ll use <code class="language-plaintext highlighter-rouge">clang++</code> or
<code class="language-plaintext highlighter-rouge">g++</code>. It’s crucial to include debug info so the debugger can show
source lines and variable names. For example:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>clang++ -g -O0 -std=c++17 -o nullptr_bug nullptr_bug.cpp
</code></pre></div></div>

<p>Here <code class="language-plaintext highlighter-rouge">-g</code> generates debug symbols (so we can see source and variables in
LLDB)<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=match%20at%20L204%20The%20compiler,as%20opposed%20to%20deployment">[1]</a>,
and <code class="language-plaintext highlighter-rouge">-O0</code> disables optimizations (making debugging easier by preserving
the code structure).</p>

<p><strong>Step 2: Launch LLDB and load the program.</strong> In a Terminal, run:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>lldb nullptr_bug
</code></pre></div></div>

<p>This starts LLDB and drops you at the <code class="language-plaintext highlighter-rouge">(lldb)</code> prompt with our program
loaded. You can also do <code class="language-plaintext highlighter-rouge">lldb</code> then <code class="language-plaintext highlighter-rouge">target create "nullptr_bug"</code> –
both have the same
effect<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=,lldb">[2]</a>.</p>

<p><strong>Step 3: Set a breakpoint (optional).</strong> In this simple case, we can
actually let the program crash and LLDB will break on the fault
automatically. But as a senior engineer, you might set a breakpoint to
inspect state before the crash. For example, set a breakpoint at the
start of <code class="language-plaintext highlighter-rouge">foo</code> to check the pointer value:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) break set -f nullptr_bug.cpp -l 5 
</code></pre></div></div>

<p>This sets a breakpoint in <code class="language-plaintext highlighter-rouge">nullptr_bug.cpp</code> at line 5 (inside <code class="language-plaintext highlighter-rouge">foo</code>).
You could also do <code class="language-plaintext highlighter-rouge">(lldb) b foo</code> to break at function <code class="language-plaintext highlighter-rouge">foo()</code>. LLDB will
confirm the breakpoint is set.</p>

<p><strong>Step 4: Run the program in the debugger.</strong> Type <code class="language-plaintext highlighter-rouge">run</code> (or <code class="language-plaintext highlighter-rouge">r</code>) at the
<code class="language-plaintext highlighter-rouge">(lldb)</code> prompt:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) run
Process 12345 launched: './nullptr_bug' (x86_64)
</code></pre></div></div>

<p>LLDB starts executing the program. If you set a breakpoint at <code class="language-plaintext highlighter-rouge">foo</code>,
execution will pause there before the crash. If not, it will run until
the crash occurs. In our case, if we didn’t set any breakpoint, LLDB
will break at the crash point. Suppose we didn’t break early — we
would see something like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Process 12345 stopped
* thread #1: hit 0x0000000100001145 nullptr_bug`foo(ptr=0x0) at nullptr_bug.cpp:6, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)[3]
</code></pre></div></div>

<p>This message tells us the program stopped due to a bad memory access. It
even shows that in <code class="language-plaintext highlighter-rouge">foo(ptr=0x0)</code> at line 6, <code class="language-plaintext highlighter-rouge">ptr</code> was <code class="language-plaintext highlighter-rouge">0x0</code> (NULL)! We
have already a huge clue: <code class="language-plaintext highlighter-rouge">ptr</code> is null.</p>

<p><strong>Step 5: Examine the call stack.</strong> In LLDB, use the <code class="language-plaintext highlighter-rouge">bt</code> (backtrace)
command to see the call stack:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) bt
* thread #1, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
  * frame #0: foo(int* ptr) at nullptr_bug.cpp:6
    frame #1: main() at nullptr_bug.cpp:12
</code></pre></div></div>

<p>This shows that we’re in <code class="language-plaintext highlighter-rouge">foo</code>, called from
<code class="language-plaintext highlighter-rouge">main</code><a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=,fib%28n%3D2%29%20%2B%2071%20at">[4]</a>.
Only two frames – it’s a simple program. Frame #0 is <code class="language-plaintext highlighter-rouge">foo</code> where the
crash happened, frame #1 is <code class="language-plaintext highlighter-rouge">main</code>. The senior engineer notes <em>where</em> in
the code the crash occurred (line 6 in <code class="language-plaintext highlighter-rouge">foo</code>) and the call path.</p>

<p><strong>Step 6: Inspect variables and memory.</strong> Let’s confirm the pointer
value. We can switch to the crashing frame and print <code class="language-plaintext highlighter-rouge">ptr</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) frame variable ptr
(int *) ptr = 0x0000000000000000
</code></pre></div></div>

<p>This confirms <code class="language-plaintext highlighter-rouge">ptr</code> is <code class="language-plaintext highlighter-rouge">0x0</code>. We’ve found the bug: <code class="language-plaintext highlighter-rouge">foo</code> was called with
a null pointer. We can also list local variables with <code class="language-plaintext highlighter-rouge">frame variable</code>
(or shorthand <code class="language-plaintext highlighter-rouge">fv</code>) – here it’s just <code class="language-plaintext highlighter-rouge">ptr</code>. If we had a more complex
scenario, we might use <code class="language-plaintext highlighter-rouge">p ptr</code> or <code class="language-plaintext highlighter-rouge">p *ptr</code>. (Attempting <code class="language-plaintext highlighter-rouge">p *ptr</code> now
would likely also trigger an error since that tries to read memory at
0x0.) The key insight is that <code class="language-plaintext highlighter-rouge">ptr</code> is null, which is why writing to
<code class="language-plaintext highlighter-rouge">*ptr</code> caused a crash.</p>

<p>For completeness, LLDB allows examining memory with commands like
<code class="language-plaintext highlighter-rouge">memory read &lt;address&gt;</code> if needed. Here, the address is 0, which is
invalid, so that’s not useful.</p>

<p><strong>Step 7: Identify root cause.</strong> The senior engineer’s thought process:
<em>“Why was</em> <code class="language-plaintext highlighter-rouge">ptr</code> <em>null? Oh, in</em> <code class="language-plaintext highlighter-rouge">main</code> <em>we explicitly set</em> <code class="language-plaintext highlighter-rouge">p = nullptr</code>
<em>and still passed it to</em> <code class="language-plaintext highlighter-rouge">foo</code><em>. That’s our bug – we dereferenced a
null pointer.”</em> We’ve confirmed the cause. The fix would be to either
initialize <code class="language-plaintext highlighter-rouge">p</code> properly or add a null check in <code class="language-plaintext highlighter-rouge">foo</code>.</p>

<p><strong>Watchpoints in LLDB:</strong> In this case, a watchpoint isn’t needed (we
directly caught the crash). But as a note, LLDB can set <em>watchpoints</em> to
monitor memory reads/writes. For example, if we wanted to break whenever
a variable changes or a certain address is accessed, we could use:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) watchpoint set variable -w write ptr   // break when 'ptr' is written
</code></pre></div></div>

<p>or watch an address:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) watchpoint set expression -w write -- &lt;address&gt;[5] 
</code></pre></div></div>

<p>This is more useful in the next scenarios (e.g. catching <em>who</em> modifies
a pointer). Keep this in mind as a powerful technique.</p>

<p>LLDB summary: we compiled with symbols, ran the program, LLDB stopped at
the crash, and we used the stack trace and variable inspection to
determine that a null pointer caused the crash. The entire process was
quick – much better than guessing from just a “Segmentation fault”
message!</p>

<h3 id="debugging-with-windbg-windows">Debugging with WinDbg (Windows)</h3>

<p>Next, let’s see how a Windows expert would debug the <strong>same null pointer
crash</strong> using WinDbg. We assume we compiled the program with MSVC in
Debug mode (which produces a <code class="language-plaintext highlighter-rouge">.pdb</code> symbol file). For example, from the
Developer Command Prompt:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cl /Zi /Od /Fe:nullptr_bug.exe nullptr_bug.cpp
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">/Zi</code> generates debug symbols (PDB), and <code class="language-plaintext highlighter-rouge">/Od</code> disables optimizations.
Now we have <code class="language-plaintext highlighter-rouge">nullptr_bug.exe</code> and a PDB for debugging.</p>

<p><strong>Step 1: Launch WinDbg and load the program.</strong> Open <strong>WinDbg</strong> (the
<strong>Desktop</strong> or <strong>Preview</strong> version). In the menu, choose <strong>File -&gt;
Launch Executable</strong> and select <code class="language-plaintext highlighter-rouge">nullptr_bug.exe</code>. WinDbg will start the
process in a paused state at the entry point (it typically breaks on an
initial breakpoint in <code class="language-plaintext highlighter-rouge">ntdll</code> or at program start). You’ll see something
like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(0:000&gt; break instruction exception - code 80000003)
</code></pre></div></div>

<p>This is the initial break. Before we continue, ensure WinDbg has loaded
symbols for our app. WinDbg might load the PDB automatically if it’s in
the same directory. You can verify by the command: <code class="language-plaintext highlighter-rouge">.sympath</code> to check
symbol path (or use <code class="language-plaintext highlighter-rouge">.symfix</code> to set up Microsoft symbol servers for
system libraries, if needed) and <code class="language-plaintext highlighter-rouge">.reload</code> to reload
symbols<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/getting-started-with-windbg#:~:text=3,readable%20function%20and%20variable%20names">[6]</a><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/getting-started-with-windbg#:~:text=Then%2C%20enter%20this%20command%3A">[7]</a>.
For our own program, it should find the PDB locally.</p>

<p><strong>Step 2: Run the program (go).</strong> At the <code class="language-plaintext highlighter-rouge">0:000&gt;</code> prompt, type <code class="language-plaintext highlighter-rouge">g</code> and
hit Enter. This resumes the program. We haven’t set any breakpoints yet,
so it will run until something noteworthy happens – in this case, the
crash.</p>

<p><strong>Step 3: Observe the crash in WinDbg.</strong> When the null pointer
dereference occurs, WinDbg breaks execution and prints an exception
message. We expect an <strong>access violation (0xC0000005)</strong> since we tried
to write to address 0. For example, WinDbg might show:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(1234.5678): Access violation - code c0000005 (first chance)[8]
</code></pre></div></div>

<p>This means thread <code class="language-plaintext highlighter-rouge">1234.5678</code> threw an access violation. “First chance”
indicates the exception is caught at the point of occurrence (you get a
“second chance” message if it was unhandled and the program is about to
terminate). In our case it’s unhandled, so WinDbg will catch it as a
second-chance exception too. The key part is <code class="language-plaintext highlighter-rouge">code c0000005</code>, the code
for access violation, and it likely says <strong>reading or writing address
0x00000000</strong>. WinDbg might also indicate if it was a read or write. If
you see
<code class="language-plaintext highlighter-rouge">Access violation - code c0000005 (first/second chance not available)</code>
that means it’s breaking on an unhandled
exception<a href="https://levelblue.com/blogs/spiderlabs-blog/windows-debugging-exploiting-part-3-windbg-time-travel-debugging#:~:text=0%3A000,first%2Fsecond%20chance%20not%20available">[8]</a>.</p>

<p>Now the program is paused exactly at the faulting instruction. The
command prompt changes to something like <code class="language-plaintext highlighter-rouge">0:000&gt;</code> (or maybe <code class="language-plaintext highlighter-rouge">0:001&gt;</code> if
multiple threads). We’re in break mode ready to investigate.</p>

<p><strong>Step 4: Check the call stack.</strong> Use the <code class="language-plaintext highlighter-rouge">k</code> command to get a stack
trace. <code class="language-plaintext highlighter-rouge">k</code> (or <code class="language-plaintext highlighter-rouge">kb</code> for more detail) will list the stack frames.
Example:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:000&gt; k
 # Child-SP          RetAddr           Call Site
00 0019fed0 00401016 nullptr_bug!foo(int*) [nullptr_bug.cpp @ 6] 
01 0019fee0 00401030 nullptr_bug!main [nullptr_bug.cpp @ 11] 
02 0019ff20 76ab7bd4 nullptr_bug!__tmainCRTStartup ... 
03 0019ff30 76c0ce51 KERNEL32!BaseThreadInitThunk ...
04 0019ff60 76d8e4b1 ntdll!RtlUserThreadStart ...
</code></pre></div></div>

<p>Frames <strong>0</strong> and <strong>1</strong> correspond to our code (addresses in
<code class="language-plaintext highlighter-rouge">nullptr_bug!foo</code> and <code class="language-plaintext highlighter-rouge">nullptr_bug!main</code>). We see <code class="language-plaintext highlighter-rouge">foo(int*)</code> at line 6
and <code class="language-plaintext highlighter-rouge">main</code> at line 11. The rest are CRT and system startup frames. So
just like in LLDB, we know we crashed in <code class="language-plaintext highlighter-rouge">foo</code>, called from <code class="language-plaintext highlighter-rouge">main</code>.
Good.</p>

<p><strong>Step 5: Inspect variables in the crashing frame.</strong> We want to see the
value of <code class="language-plaintext highlighter-rouge">ptr</code> in <code class="language-plaintext highlighter-rouge">foo</code>. Since we have debug symbols, we can use the
<strong>Local Variables window</strong> or the <code class="language-plaintext highlighter-rouge">dv</code> command. Let’s try <code class="language-plaintext highlighter-rouge">dv</code> (Display
Variables):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:000&gt; dv
               ptr = 0x00000000
</code></pre></div></div>

<p>WinDbg shows that <code class="language-plaintext highlighter-rouge">ptr</code> is 0x00000000 (NULL). That confirms our
suspicion. We could also use the newer <code class="language-plaintext highlighter-rouge">.frame</code> syntax or the
NatVis/WinDbg Preview Locals pane, but <code class="language-plaintext highlighter-rouge">dv</code> is quick and shows the local
variables and arguments in the current
frame<a href="https://medium.com/ax1al/introduction-to-windbg-1177487c77a4#:~:text=Medium%20medium,the%20type%20of%20the">[9]</a>.
We see <code class="language-plaintext highlighter-rouge">ptr</code> is null. Alternatively, we could evaluate <code class="language-plaintext highlighter-rouge">ptr</code> with the
<code class="language-plaintext highlighter-rouge">?</code> or <code class="language-plaintext highlighter-rouge">dx</code> command (for instance, <code class="language-plaintext highlighter-rouge">? ptr</code> or <code class="language-plaintext highlighter-rouge">dx ptr</code>), but <code class="language-plaintext highlighter-rouge">dv</code>
already gave us the answer in a straightforward way.</p>

<p><strong>Step 6: (Optional) Breakpoints and watchpoints.</strong> In this simple run,
we didn’t set any breakpoints – we just let the program crash. If we
wanted, we could have set a breakpoint at <code class="language-plaintext highlighter-rouge">nullptr_bug!foo</code> before
running. In WinDbg, you can set a breakpoint by function name or source
line. For example:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:000&gt; bu nullptr_bug!foo    ; (bu = break on symbol, unresolved is okay)
0:000&gt; g
</code></pre></div></div>

<p>This would break at the start of <code class="language-plaintext highlighter-rouge">foo</code>. Once hit, we could inspect <code class="language-plaintext highlighter-rouge">ptr</code>
before it’s used. In more complex scenarios, that’s useful to catch
issues before the actual crash.</p>

<p>For <em>watchpoints</em> (called <strong>data breakpoints</strong> in WinDbg), WinDbg uses
the <code class="language-plaintext highlighter-rouge">ba</code> (Break on Access) command. In this case, a watchpoint isn’t
necessary, but to illustrate: if we wanted to break when a certain
memory address is accessed, we could do <code class="language-plaintext highlighter-rouge">ba &lt;access&gt; &lt;size&gt; &lt;address&gt;</code>.
For example, <code class="language-plaintext highlighter-rouge">ba w 4 0x0</code> would break on any write of 4 bytes to address
0 (not very useful here since that always crashes anyway). A more
realistic use: we’ll see in the next case how to break on access to
freed memory. Just remember that in WinDbg, <code class="language-plaintext highlighter-rouge">ba w 4 &lt;addr&gt;</code> means “break
on 4-byte writes to
&lt;addr&gt;”<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-#:~:text=Option%20Action">[10]</a><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-#:~:text=This%20example%20sets%20a%20conditional,the%20debugger%20should%20break%20in">[11]</a>.</p>

<p><strong>Step 7: Identify the root cause.</strong> The call stack and variable state
make it clear: <code class="language-plaintext highlighter-rouge">ptr</code> was null when we tried to use it, leading to the
access violation. The senior engineer concludes: <em>“We passed a null
pointer into</em> <code class="language-plaintext highlighter-rouge">foo</code> <em>– there’s no check, so it crashed. The bug is the
null pointer usage.”</em></p>

<p>We’d fix it similarly (initialize <code class="language-plaintext highlighter-rouge">p</code> or avoid calling <code class="language-plaintext highlighter-rouge">foo</code> with null).
WinDbg successfully helped us confirm the issue.</p>

<h3 id="debugging-with-vs-code--codelldb-macos">Debugging with VS Code + <strong>CodeLLDB</strong> (macOS)</h3>

<p>Now let’s see the same bug through the lens of VS Code on macOS, using
the <strong>CodeLLDB</strong> extension. This gives us a graphical interface but
still uses LLDB under the hood. The process will be familiar but with a
friendlier UI.</p>

<p><strong>Step 1: Compile the program.</strong> We use the same compile command as in
the LLDB section (clang++ or g++ with <code class="language-plaintext highlighter-rouge">-g</code>). Suppose we have
<code class="language-plaintext highlighter-rouge">nullptr_bug.cpp</code> in a VS Code workspace. We compile it (via a VS Code
task or manually in Terminal):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>clang++ -g -O0 -o nullptr_bug nullptr_bug.cpp
</code></pre></div></div>

<p><strong>Step 2: Set up debugging in VS Code.</strong> Open the folder in VS Code.
Install the <strong>CodeLLDB</strong> extension (if not already). Go to the Run and
Debug view (the Debug sidebar) and create a launch configuration. VS
Code might auto-detect and suggest a configuration for LLDB. For
example, your <code class="language-plaintext highlighter-rouge">.vscode/launch.json</code> might have:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>{
    "name": "Debug nullptr_bug",
    "type": "lldb",
    "request": "launch",
    "program": "${workspaceFolder}/nullptr_bug",
    "args": [],
    "cwd": "${workspaceFolder}"
}
</code></pre></div></div>

<p>This tells VS Code to use the CodeLLDB debugger to launch our compiled
program. (The <code class="language-plaintext highlighter-rouge">"type": "lldb"</code> comes from the CodeLLDB extension.) Make
sure the path to the program is correct.</p>

<p><strong>Step 3: Set a breakpoint in the source.</strong> Open <code class="language-plaintext highlighter-rouge">nullptr_bug.cpp</code> in
the editor. Click in the gutter next to the line where <code class="language-plaintext highlighter-rouge">foo</code>
dereferences the pointer (line 6) or at the call in main. As a senior
engineer, I might set a breakpoint at <code class="language-plaintext highlighter-rouge">foo(ptr=...)*ptr = 42</code> line to
pause just before the crash. A red dot will appear indicating the
breakpoint is set. (Alternatively, you could skip setting any breakpoint
– the debugger will stop on the exception anyway. But let’s do it to
demonstrate normal debugging.)</p>

<p><strong>Step 4: Start debugging.</strong> Click the <strong>Run and Debug</strong> button (green
triangle or press F5). VS Code will launch the program under the
debugger. If you set a breakpoint, execution will pause at that line. If
not, it will run and then pause when the crash occurs.</p>

<p>Let’s assume we set the breakpoint at <code class="language-plaintext highlighter-rouge">*ptr = 42</code>. The debugger stops
there, highlighting the line in the source code. In the <strong>Debug
toolbar</strong> you’ll see controls (Continue, Step Over, Step Into, etc.),
and in the sidebar you’ll see <strong>Variables, Call Stack, Breakpoints,</strong>
etc. The <strong>Variables</strong> pane shows local variables in the current
function. We should see something like:</p>

<ul>
  <li><strong>Local</strong>: <code class="language-plaintext highlighter-rouge">ptr = 0x0</code></li>
</ul>

<p>Yes, VS Code’s Variables view will show that <code class="language-plaintext highlighter-rouge">ptr</code> is <code class="language-plaintext highlighter-rouge">0x0</code> (null) at
this breakpoint. We haven’t even continued to the crash – we caught it
right before. This is great: as a senior engineer, I suspected a null
pointer, and the breakpoint confirms it.</p>

<p><strong>Step 5: Step or continue to observe the crash.</strong> If we hit the
<strong>Continue</strong> button (or press F5 again), the program will attempt to
execute the <code class="language-plaintext highlighter-rouge">*ptr = 42</code> line. Since <code class="language-plaintext highlighter-rouge">ptr</code> is 0, a crash will occur.
CodeLLDB will then break execution and likely show a popup or message
like “Program received signal SIGSEGV”. VS Code might switch to a
disassembly view if it doesn’t know where in source to show the crash
(since we continued past our last breakpoint into a crash). Don’t worry
– we can still debug. The <strong>Call Stack</strong> pane now likely shows an entry
for <code class="language-plaintext highlighter-rouge">foo</code> and <code class="language-plaintext highlighter-rouge">main</code>, similar to before. You can click on <code class="language-plaintext highlighter-rouge">foo</code> in the
call stack to open the source at that frame. The Variables pane still
shows <code class="language-plaintext highlighter-rouge">ptr = 0x0</code>.</p>

<p><strong>Step 6: Inspect variables and call stack.</strong> In VS Code, much of this
is done via the UI: the call stack is already visible, and local
variables are listed. We can hover over <code class="language-plaintext highlighter-rouge">ptr</code> in the editor to see its
value (a tooltip shows 0x0). We can also open the <strong>Debug Console</strong> and
use LLDB commands or expressions. For example, we could type <code class="language-plaintext highlighter-rouge">print ptr</code>
or <code class="language-plaintext highlighter-rouge">p ptr</code> in the Debug Console. CodeLLDB will execute that via LLDB and
print the result. Since <code class="language-plaintext highlighter-rouge">ptr</code> is simple, the UI already told us it’s
null, so we’re good.</p>

<p>If we wanted the backtrace textually, we could use the Debug Console to
run the <code class="language-plaintext highlighter-rouge">bt</code> command (preface it with <code class="language-plaintext highlighter-rouge">-exec</code> if needed, e.g.
<code class="language-plaintext highlighter-rouge">-exec bt</code>). But visually we can see <code class="language-plaintext highlighter-rouge">foo -&gt; main</code> in the stack list.</p>

<p><strong>Step 7: (Optional) Use watchpoints or advanced breakpoints.</strong> VS
Code’s UI (with CodeLLDB) doesn’t have a dedicated “data breakpoint”
button like the MSVC/GDB version does, but we can still do it via the
LLDB console. For instance, in the Debug Console we could run:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>-exec watchpoint set variable ptr
</code></pre></div></div>

<p>However, in this scenario we already know <code class="language-plaintext highlighter-rouge">ptr</code> is null from the get-go.
We’ll showcase watchpoints in the next case where it’s more applicable.
Just know that in CodeLLDB you have the full power of LLDB commands
available in the console, and you can also set <em>conditional breakpoints</em>
in VS Code (right-click a breakpoint -&gt; Edit Condition) if you only
want to break when a certain condition is true (e.g., break when
<code class="language-plaintext highlighter-rouge">ptr == nullptr</code>).</p>

<p><strong>Step 8: Diagnose the issue.</strong> The outcome in VS Code/CodeLLDB is the
same: we see that <code class="language-plaintext highlighter-rouge">ptr</code> is null and that caused a segmentation fault.
The senior dev confirms the bug is using a null pointer. We stop
debugging (Shift+F5) and go fix the code.</p>

<p>Using VS Code in this way can be more intuitive for those who prefer GUI
debugging: you click breakpoints and inspect variables without
memorizing commands. But under the hood, the process and the information
we gather are identical to the LLDB command-line session we did first.</p>

<h3 id="debugging-with-vs-code--cppdbg-windows--gdb">Debugging with VS Code + <strong>CppDbg</strong> (Windows / GDB)</h3>

<p>Finally, let’s reproduce the debugging process on Windows using VS Code
with the default C++ extension (cpptools), which we’ll configure to use
GDB. This setup is common if you’re using MinGW or WSL for C++
development in VS Code. (If you have Visual Studio’s debugger, you might
use the <code class="language-plaintext highlighter-rouge">"cppvsdbg"</code> type instead, but here we’ll assume a GCC/GDB
toolchain on Windows for variety.)</p>

<p><strong>Step 1: Compile the program with debug info.</strong> If using MinGW-w64 g++,
you’d do:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>g++ -g -O0 -o nullptr_bug.exe nullptr_bug.cpp
</code></pre></div></div>

<p>This produces <code class="language-plaintext highlighter-rouge">nullptr_bug.exe</code> with DWARF debug symbols that GDB can
use. If you’re instead using MSVC but still want to debug in VS Code,
you could compile with <code class="language-plaintext highlighter-rouge">/Zi</code> and configure VS Code for <code class="language-plaintext highlighter-rouge">"cppvsdbg"</code>
(Visual Studio debugger) – but we’ll stick to GDB for now.</p>

<p><strong>Step 2: Set up VS Code debugging (cppdbg).</strong> In VS Code on Windows,
install the <strong>C/C++ extension</strong> by Microsoft (if not already). Open the
folder with the program. In the Run and Debug tab, create a launch
configuration and choose the C++ (GDB/LLDB) template. You’ll get a
<code class="language-plaintext highlighter-rouge">launch.json</code> entry like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>{
    "name": "Debug nullptr_bug (GDB)",
    "type": "cppdbg",
    "request": "launch",
    "program": "${workspaceFolder}/nullptr_bug.exe",
    "cwd": "${workspaceFolder}",
    "stopAtEntry": false,
    "console": "externalConsole",
    "MIMode": "gdb",
    "miDebuggerPath": "C:/mingw/bin/gdb.exe"
}
</code></pre></div></div>

<p>Key points: <code class="language-plaintext highlighter-rouge">"type": "cppdbg"</code> and <code class="language-plaintext highlighter-rouge">"MIMode": "gdb"</code> tells VS Code to
use GDB. Make sure <code class="language-plaintext highlighter-rouge">miDebuggerPath</code> points to your GDB. Now we’re set to
debug with GDB through VS Code.</p>

<p><strong>Step 3: Set a breakpoint.</strong> Just like before, open the source file in
VS Code and click to set a breakpoint at the <code class="language-plaintext highlighter-rouge">*ptr = 42</code> line (or
anywhere you want to pause). Let’s do the same line.</p>

<p><strong>Step 4: Start debugging.</strong> Press F5 to launch. An external console
opens (since we set <code class="language-plaintext highlighter-rouge">"externalConsole": true</code> for MinGW), and VS Code
attaches GDB to our program. The program will run until the breakpoint
is hit. VS Code will highlight the line and show “Paused on breakpoint”.</p>

<p>Look at the <strong>Variables</strong> pane – with GDB it should show local
variables as well. You’ll see <code class="language-plaintext highlighter-rouge">ptr = 0x0</code>. The <strong>Call Stack</strong> pane shows
<code class="language-plaintext highlighter-rouge">foo</code> and <code class="language-plaintext highlighter-rouge">main</code> similar to before. So far, so good.</p>

<p><strong>Step 5: Continue to crash.</strong> If we continue execution, the program
will attempt the write and crash. GDB will stop with a SIGSEGV signal.
VS Code should display something like “Segmentation fault (SIGSEGV)” in
the Debug Console or as a notification. The stack and variables are
still available for inspection. You might see the console output say
"<strong>Program received signal SIGSEGV, Segmentation fault.</strong>" and
indicate the line of crash. GDB has broken at the point of failure.</p>

<p><strong>Step 6: Inspect the state.</strong> We again confirm <code class="language-plaintext highlighter-rouge">ptr</code> is null (0x0) via
the Variables pane. We can also use the <strong>Debug Console</strong> to run GDB
commands if needed (for example, <code class="language-plaintext highlighter-rouge">info locals</code> or <code class="language-plaintext highlighter-rouge">print ptr</code>). The call
stack is visible; if you expand the stack frames, it may show
<code class="language-plaintext highlighter-rouge">foo(int*)</code> and <code class="language-plaintext highlighter-rouge">main</code> with line numbers. Everything confirms the null
pointer scenario.</p>

<p><strong>Step 7: Data breakpoints (watchpoints) in VS Code/GDB.</strong> While not
needed here, it’s worth noting that the VS Code C++ extension supports
<strong>Data Breakpoints</strong> with GDB. For instance, we could have set a data
breakpoint on <code class="language-plaintext highlighter-rouge">ptr</code> if it was a global or on an address. In VS Code, you
can right-click a variable in the Variables list and choose <strong>“Break on
Value Change”</strong> to create a data
breakpoint<a href="https://devblogs.microsoft.com/cppblog/whats-new-for-c-debugging-in-visual-studio-code/#:~:text=To%20set%20a%20data%20breakpoint,select%20Break%20on%20Value%20Change">[12]</a>.
(This sets a hardware watchpoint in GDB for that variable’s address.) If
we had done that for a global pointer or some memory address, the
debugger would break when it changes. For a local like <code class="language-plaintext highlighter-rouge">ptr</code>, this
feature is more useful in later scenarios (like watching a global
pointer that might be freed by another thread). We’ll use this in the
multi-threaded case.</p>

<p><strong>Step 8: Conclusion of analysis.</strong> The VS Code + GDB run yields the
same conclusion: the pointer is null and that’s the bug. The senior
engineer notes the fix as before. We stop debugging and resolve the
issue in code.</p>

<hr />

<p>We have now debugged the same null pointer crash with four different
tools/environments. The outcome was identical in each: by using
breakpoints or catching the exception, we inspected the call stack and
saw the null pointer value, pinpointing the root cause. Along the way,
we used each tool’s features (like <code class="language-plaintext highlighter-rouge">bt</code> in LLDB/WinDbg, the VS Code UI,
etc.).</p>

<p>Before moving on, key transferable techniques from this case: always
compile with debug symbols for easier
debugging<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=match%20at%20L204%20The%20compiler,as%20opposed%20to%20deployment">[1]</a>,
let the program run under the debugger to catch crashes, use the call
stack to find where the crash happened, and inspect variable values to
diagnose the cause. Next, we’ll apply these techniques to more complex
bugs.</p>

<h2 id="case-study-2-use-after-free-memory-error-heap-corruption">Case Study 2: Use-After-Free Memory Error (Heap Corruption)</h2>

<p><strong>The Bug:</strong> In this case, we have a program that allocates memory,
frees it, and then mistakenly uses the freed memory. This is a
<em>use-after-free</em> bug. Such issues can cause crashes, memory corruption,
or bizarre behavior. We’ll use a simple example that may or may not
crash immediately, illustrating how debuggers can help catch the misuse
of freed memory.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#include &lt;iostream&gt;
#include &lt;cstdlib&gt;

int main() {
    int *arr = (int*) std::malloc(5 * sizeof(int));
    for (int i = 0; i &lt; 5; ++i) arr[i] = i;   // fill the array
    std::free(arr);
    // Bug: use-after-free
    std::cout &lt;&lt; "Element[0] after free: " &lt;&lt; arr[0] &lt;&lt; std::endl;
    // Also a double free for demonstration
    std::free(arr);  // freeing again - double free
    return 0;
}
</code></pre></div></div>

<p>In this code, we free <code class="language-plaintext highlighter-rouge">arr</code> and then <strong>immediately try to read</strong>
<code class="language-plaintext highlighter-rouge">arr[0]</code>. This is undefined behavior – the memory is freed, so reading
it is an error. We even call <code class="language-plaintext highlighter-rouge">free(arr)</code> a second time, which is a
double free bug. Depending on the environment, this might crash or it
might appear to “work” while corrupting the heap. For example, on some
systems this program might print the old value for <code class="language-plaintext highlighter-rouge">arr[0]</code> and only
crash later (or terminate normally but poison the heap). On others, the
runtime might detect the double free and abort the program. We’ll see
how to debug such issues by detecting the misuse of freed memory.</p>

<h3 id="debugging-with-lldb-macos-1">Debugging with LLDB (macOS)</h3>

<p><strong>Step 1: Compile with debug info.</strong> As before, compile with <code class="language-plaintext highlighter-rouge">-g</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>clang++ -g -O0 -o use_after_free use_after_free.cpp
</code></pre></div></div>

<p><strong>Step 2: Run under LLDB.</strong> Launch LLDB with the program:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>lldb use_after_free
(lldb) run
</code></pre></div></div>

<p>Now, observe what happens. Since this bug may not crash immediately, we
might see the program’s output in LLDB:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/*** Running ***/
Element[0] after free: 0
Process 18103 exited with status 0
</code></pre></div></div>

<p>Imagine LLDB shows that the program ran to completion printing
“Element[0] after free: 0”. No obvious crash happened. That’s actually
worse – the bug didn’t crash, so it could silently corrupt memory. The
senior engineer suspects something’s wrong because reading memory after
free is illegal. How do we catch it? We use debugger tools smartly:</p>

<p><strong>Step 3: Break on the</strong> <code class="language-plaintext highlighter-rouge">free</code> <strong>and watch the memory.</strong> A technique
for use-after-free: set a breakpoint at <code class="language-plaintext highlighter-rouge">free()</code> to capture the address
being freed, then set a <em>watchpoint</em> on that memory so we break if it’s
accessed later.</p>

<p>In LLDB: we set a breakpoint on <code class="language-plaintext highlighter-rouge">free</code> (the C library function).</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) b free
Breakpoint 1: where = libsystem_malloc.dylib`free, address = 0x7fff... 
</code></pre></div></div>

<p>Run the program again: <code class="language-plaintext highlighter-rouge">(lldb) run</code>. The program will break when it
calls <code class="language-plaintext highlighter-rouge">free(arr)</code>. We hit the breakpoint inside the <code class="language-plaintext highlighter-rouge">free</code> function
(LLDB will show a stop in the memory allocator code). We can get the
argument to <code class="language-plaintext highlighter-rouge">free</code> by inspecting registers or use a backtrace to our
code. An easier way: look at the call stack to find our <code class="language-plaintext highlighter-rouge">main</code> frame.
Use <code class="language-plaintext highlighter-rouge">bt</code> and find the frame in our code that called free. For example:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) bt
* thread #1, stop reason = breakpoint 1
  * frame #0: 0x7fff... libsystem_malloc.dylib`free
    frame #1: 0x0000000100000abc use_after_free`main + 60 at use_after_free.cpp:7
</code></pre></div></div>

<p>Frame #1 is our <code class="language-plaintext highlighter-rouge">main</code> at the line calling <code class="language-plaintext highlighter-rouge">free</code>. Let’s select that:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) frame select 1
(lldb) print arr
(int *) $0 = 0x0000000102b00510
</code></pre></div></div>

<p>We got the address of <code class="language-plaintext highlighter-rouge">arr</code> that’s being freed (say it’s <code class="language-plaintext highlighter-rouge">0x102b00510</code>).
Now we’ll set a watchpoint on that memory. We know <code class="language-plaintext highlighter-rouge">arr</code> points to 5
ints, so 20 bytes. We can watch the first 4 bytes for any access
(read/write).</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) watchpoint set expression -w read_write -- arr
Watchpoint created: Watchpoint 2: addr = 0x0000000102b00510 size = 8 state = enabled
</code></pre></div></div>

<p>We set a watchpoint on that address (LLDB chooses size 8 by default
here, which covers at least the first int and
more)<a href="https://gist.github.com/rais38/6ecead686af9291da542#:~:text=Set%20a%20watchpoint%20on%20a,a%20condition%20on%20a%20watchpoint">[13]</a>.
Now continue execution:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) c   // continue
</code></pre></div></div>

<p>LLDB will continue until something accesses that memory. In our program,
the next line tries <code class="language-plaintext highlighter-rouge">arr[0]</code> which is a read of the just-freed address.
That should trigger our watchpoint. Indeed, LLDB should stop and report
the watchpoint:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Process 18103 stopped
* thread #1: stop reason = watchpoint 2
    frame #0: 0x0000000100000aeb use_after_free`main + 75 at use_after_free.cpp:8
   6    std::free(arr);
-&gt; 7    std::cout &lt;&lt; "Element[0] after free: " &lt;&lt; arr[0] &lt;&lt; std::endl;
</code></pre></div></div>

<p>It breaks at line 7 (the use-after-free) because the watchpoint caught
our read of the freed memory. LLDB prints that it’s a watchpoint and
we’re in <code class="language-plaintext highlighter-rouge">main</code> at that
line<a href="https://gist.github.com/rais38/6ecead686af9291da542#:~:text=...%20%28lldb%29%20bt%20,int32_t%29%20global%20%3D%205">[14]</a>.
Now we caught the bug red-handed <em>before</em> any weird behavior.</p>

<p><strong>Step 4: Inspect variables and memory.</strong> We know <code class="language-plaintext highlighter-rouge">arr</code> is the freed
pointer. We can confirm:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) print arr
(int *) $1 = 0x0000000102b00510
</code></pre></div></div>

<p>It’s the same address freed earlier. If we want, we can check if maybe
the allocator has overwritten it with a pattern. Often, debug allocators
might fill freed memory with 0xDEADBEEF or 0xDD… in hex. We can
examine memory:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) memory read 0x0000000102b00510 0x0000000102b00530
</code></pre></div></div>

<p>This would show the bytes at that address. (We might see some pattern or
the old data.) The specifics aren’t crucial – the main point is we
<strong>caught a use-after-free</strong>. The senior engineer’s thought: <em>“The
program is reading memory that was freed. That’s a bug. Also, it calls
free twice on the same pointer, which is another bug.”</em></p>

<p><strong>Step 5: Double-free detection.</strong> After the watchpoint break, if we
continue, the program may hit the second <code class="language-plaintext highlighter-rouge">free(arr)</code>. Many allocators
will detect this and abort. If we hadn’t caught the watchpoint, LLDB
likely would have stopped when the second free caused a crash or an
abort signal. For example, macOS’s malloc might throw an error and halt
the program. In LLDB, you’d see a stop with a message about double free
or an <code class="language-plaintext highlighter-rouge">abort</code> signal. We can simulate continuing:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) c
Process 18103 stopped
* thread #1: stop reason = signal SIGABRT
    frame #0: 0x7fff... libsystem_malloc.dylib`free
</code></pre></div></div>

<p>This indicates the program aborted (SIGABRT) in <code class="language-plaintext highlighter-rouge">free</code>, likely due to
heap corruption (double free). We could again inspect the call stack and
see it was the second call to free in <code class="language-plaintext highlighter-rouge">main</code>.</p>

<p><strong>Step 6: Diagnose the issue.</strong> Using LLDB, we systematically caught the
misuse. The output “Element[0] after free: 0” was a red flag (why is
it printing a value after free?). By setting a watchpoint, we confirmed
<code class="language-plaintext highlighter-rouge">arr[0]</code> was accessed after free. The double free was caught by the
runtime abort. The root causes: use-after-free and double-free. A fix
would be to remove the extra <code class="language-plaintext highlighter-rouge">free</code> and ensure we don’t use memory after
freeing (perhaps set <code class="language-plaintext highlighter-rouge">arr = nullptr</code> after free and check it).</p>

<p>The key takeaway here is how to use breakpoints and watchpoints to catch
memory errors <em>even when the program doesn’t crash exactly at the point
of misuse</em>. We essentially forced a stop at the point of invalid access.</p>

<h3 id="debugging-with-windbg-windows-1">Debugging with WinDbg (Windows)</h3>

<p>On Windows, the C runtime has its own debug mechanisms for heap issues,
but let’s see how to catch the use-after-free with WinDbg.</p>

<p><strong>Step 1: Compile for Windows (Debug mode).</strong> If using MSVC, compile
with debug symbols (<code class="language-plaintext highlighter-rouge">/Zi</code>). If using MinGW, similar approach – but
let’s assume MSVC for WinDbg to leverage the CRT’s checks. For instance:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cl /Zi /Od /RTC1 /MDd use_after_free.cpp /Fe:use_after_free.exe
</code></pre></div></div>

<p>Here, <code class="language-plaintext highlighter-rouge">/RTC1</code> (Runtime Checks) and <code class="language-plaintext highlighter-rouge">/MDd</code> (Debug CRT) enable extra heap
checks. The Debug CRT will often catch double frees by crashing
immediately with an error message. So our program might actually crash
on the second <code class="language-plaintext highlighter-rouge">free</code> with an assertion. If that happens, WinDbg will
break on it. Let’s proceed.</p>

<p><strong>Step 2: Launch under WinDbg and run.</strong></p>

<ul>
  <li>Start WinDbg and open <code class="language-plaintext highlighter-rouge">use_after_free.exe</code> (File -&gt; Launch
Executable).</li>
  <li>Set a breakpoint at the C runtime free or at our code after the first
free. One strategy: break on <code class="language-plaintext highlighter-rouge">ntdll!RtlFreeHeap</code> which is underlying
Windows heap free, or on the CRT <code class="language-plaintext highlighter-rouge">free</code>. For simplicity, let’s break
on <code class="language-plaintext highlighter-rouge">free</code> like we did in LLDB:</li>
</ul>

<!-- -->

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:000&gt; bu ucrtbased!free
</code></pre></div></div>

<p>(<code class="language-plaintext highlighter-rouge">ucrtbased</code> is the debug CRT library in MSVC; in release it would be
<code class="language-plaintext highlighter-rouge">ucrtbase</code> or MSVCRT.) WinDbg sets the breakpoint.</p>

<ul>
  <li>Now <code class="language-plaintext highlighter-rouge">g</code> to run. The program breaks at the first <code class="language-plaintext highlighter-rouge">free(arr)</code>. We see a
break in <code class="language-plaintext highlighter-rouge">ucrtbased!free</code>.</li>
</ul>

<p><strong>Step 3: Find the address being freed.</strong> Similar to LLDB, check the
call stack to find our frame:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:000&gt; k
 # Child-SP    RetAddr     Call Site
00 0019f7c0 74f3abc1 ucrtbased!free(void * block = 0x00a51020) 
01 0019f7d0 01001347 use_after_free!main+0x47 [use_after_free.cpp @ 6]
...
</code></pre></div></div>

<p>Frame 0 is inside free, it shows the argument <code class="language-plaintext highlighter-rouge">block = 0x00a51020</code> (the
address freed). Frame 1 is our <code class="language-plaintext highlighter-rouge">main</code> at line 6. So the pointer value is
<code class="language-plaintext highlighter-rouge">0x00a51020</code>. We can note this or even copy it.</p>

<p><strong>Step 4: Set a watchpoint (break on access).</strong> In WinDbg, we use the
<code class="language-plaintext highlighter-rouge">ba</code> command. We want to break on any access (read or write) to, say,
the first 4 bytes of that freed block. We take the address <code class="language-plaintext highlighter-rouge">0x00a51020</code>.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:000&gt; ba r4 00a51020 
</code></pre></div></div>

<p>This sets a data breakpoint on a 4-byte read (actually <code class="language-plaintext highlighter-rouge">r</code> means
read/write) at that
address<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-#:~:text=Option%20Action">[10]</a><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-#:~:text=Size%20Specifies%20the%20size%20of,e%2C%20Size%20must%20be%201">[15]</a>.
Now continue:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:000&gt; g
</code></pre></div></div>

<p>The program continues. Now when it executes <code class="language-plaintext highlighter-rouge">std::cout &lt;&lt; arr[0]</code>, that
tries to read <code class="language-plaintext highlighter-rouge">arr[0]</code> at <code class="language-plaintext highlighter-rouge">0x00a51020</code>. Our watchpoint should trigger on
that memory access. WinDbg breaks and shows something like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(1234.5678): Break instruction exception - code 80000003 (first chance)
Breakpoint 2 hit
use_after_free!main+0x5A at use_after_free.cpp:7
</code></pre></div></div>

<p>It indicates our data breakpoint hit at line 7 of main. Great – we
caught the use-after-free access. We can now inspect:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:000&gt; dv
       arr = 0x00a51020
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">arr</code> is still that address, now invalid. If we dump memory at that
address, the debug CRT might have filled it with a pattern (0xFEEE or
0xDD etc). We can try:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:000&gt; dd 00a51020 L1
00a51020  ???????? 
</code></pre></div></div>

<p>Sometimes in WinDbg, a freed block might show specific hex (in debug
mode, freed heap memory is usually filled with <code class="language-plaintext highlighter-rouge">0xFEEEFEEE</code> in Windows).
But even if not visible, we <em>know</em> it’s freed.</p>

<p><strong>Step 5: Continue to catch double free.</strong> If we continue again, the
second <code class="language-plaintext highlighter-rouge">free(arr)</code> will be called. The debug CRT should detect that this
block was freed already and likely trigger an assertion or throw a
safeguarded exception. WinDbg would then break (probably with an access
violation or an <code class="language-plaintext highlighter-rouge">_CrtIsValidHeapPointer</code> assertion). For example, you
might see:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(1234.5678): Invalid address specified to RtlFreeHeap( 00A50000, 00A51020 )
</code></pre></div></div>

<p>and an access violation inside heap code. The exact message can vary,
but the bottom line: WinDbg will catch it (as a second-chance exception
if the CRT aborts). The call stack would show the second call to <code class="language-plaintext highlighter-rouge">free</code>
from main.</p>

<p><strong>Step 6: Analyze root cause.</strong> We’ve used WinDbg to verify the program
freed memory and then accessed it (our watchpoint proved that), and
attempted a double free. The senior engineer notes: <em>“We have a
use-after-free (the program read memory after freeing it) and a double
free. These are serious memory corruption bugs.”</em></p>

<p>The debugging strategy here was crucial: because the program didn’t
outright crash on the first invalid access, we had to proactively break
on suspicious behavior (like calling free, then watching that memory).
This is a common pattern in debugging heap corruption – catch the
moment of misuse rather than the aftermath.</p>

<h3 id="debugging-with-vs-code--codelldb-macos-1">Debugging with VS Code + CodeLLDB (macOS)</h3>

<p>In VS Code with CodeLLDB, we don’t have an out-of-the-box UI feature to
set a watchpoint on an arbitrary address, but we can still catch this
bug using a mix of breakpoints and the LLDB console.</p>

<p><strong>Step 1: Compile with -g</strong> (as done before). Open in VS Code, ensure
CodeLLDB is configured.</p>

<p><strong>Step 2: Set a breakpoint on</strong> <code class="language-plaintext highlighter-rouge">free</code><strong>.</strong> This is tricky in VS Code’s
UI because <code class="language-plaintext highlighter-rouge">free</code> is a C library function not in our code. But we can
use the debug console. Alternatively, you can add an entry in
<code class="language-plaintext highlighter-rouge">launch.json</code> for a function breakpoint (VS Code allows specifying
function names in the launch config’s <code class="language-plaintext highlighter-rouge">"functionBreakpoint"</code> section or
using the UI’s <strong>Add Function Breakpoint</strong> in the Breakpoints view).
Let’s do that: in VS Code’s Breakpoints pane, click <strong>"+"</strong> &gt;
<strong>Function Breakpoint</strong>, and enter <code class="language-plaintext highlighter-rouge">free</code>. VS Code (via LLDB) will set a
breakpoint on <code class="language-plaintext highlighter-rouge">free()</code>.</p>

<p><strong>Step 3: Start debugging.</strong> Run under the debugger. The program will
break when <code class="language-plaintext highlighter-rouge">free</code> is called (just like our LLDB CLI session did). VS
Code will likely show assembly or indicate we’re in <code class="language-plaintext highlighter-rouge">free</code> (which is
outside our source). Look at the call stack: one frame will be <code class="language-plaintext highlighter-rouge">free</code>,
and below it our <code class="language-plaintext highlighter-rouge">main</code>. Click the <code class="language-plaintext highlighter-rouge">main</code> frame to see our code. We’re
at the line after free returned (or still on the free call). The
Variables pane shows <code class="language-plaintext highlighter-rouge">arr</code> and its value.</p>

<p><strong>Step 4: Use LLDB console to set a watchpoint.</strong> Open the Debug Console
in VS Code. We’ll issue an LLDB command to set a watchpoint on <code class="language-plaintext highlighter-rouge">arr</code>’s
memory. For example:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>-exec watchpoint set expression -w read_write -- (void*)arr
</code></pre></div></div>

<p>This tells LLDB to break on read/write to the address in <code class="language-plaintext highlighter-rouge">arr</code>. (We cast
to void* to match expression context). LLDB should respond with a
watchpoint created message. Now continue execution:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>-exec continue
</code></pre></div></div>

<p>(This is equivalent to clicking Continue). When the program tries to
read <code class="language-plaintext highlighter-rouge">arr[0]</code>, LLDB triggers the watchpoint and VS Code will break
again. It may show a message like “Watchpoint 2 hit”. We’re at the line
of <code class="language-plaintext highlighter-rouge">std::cout &lt;&lt; arr[0]</code>. Great. Now we know a use-after-free is
happening.</p>

<p><strong>Step 5: The Variables pane</strong> will still show <code class="language-plaintext highlighter-rouge">arr</code> (address). At this
point, we know it’s freed. We can optionally verify if CodeLLDB shows
any clue (in some cases, the memory might show as <code class="language-plaintext highlighter-rouge">&lt;invalid address&gt;</code> if
the debug runtime set protections, but likely it just appears as an
address). Regardless, we’ve confirmed an access to freed memory.</p>

<p><strong>Step 6: Continue to see double free reaction.</strong> Continue again. If the
program aborts on double free, CodeLLDB will break on the abort signal
(SIGABRT). VS Code might pop up “Program terminated with signal
SIGABRT”. The call stack will show it coming from <code class="language-plaintext highlighter-rouge">free</code> second time. We
gather the evidence.</p>

<p><strong>Step 7: Conclusion.</strong> The VS Code approach required some console
commands for watchpoints, but it allowed us to catch the issue
similarly. The takeaway is that even in VS Code, you can combine UI and
debugger console to leverage advanced features like watchpoints.</p>

<p><em>(If one were using AddressSanitizer or other tooling, it would catch
these errors too, but here we’re focusing on manual debugging
techniques.)</em></p>

<h3 id="debugging-with-vs-code--cppdbg-windows">Debugging with VS Code + CppDbg (Windows)</h3>

<p>Using VS Code with the Microsoft C++ extension (and GDB on Windows), we
can attempt a similar strategy. Note: The cpptools extension has a UI
for data breakpoints (as mentioned). Let’s exploit that.</p>

<p><strong>Step 1:</strong> Compile with MinGW (or MSVC). If MinGW’s GDB, same <code class="language-plaintext highlighter-rouge">-g -O0</code>.
Launch VS Code with GDB as configured.</p>

<p><strong>Step 2:</strong> We can try setting a breakpoint on free by function name in
VS Code as well (similar to above, add a Function Breakpoint for
<code class="language-plaintext highlighter-rouge">free</code>). Alternatively, since the MS C++ extension supports data
breakpoints directly, we can do a simpler trick: after the first free,
set a data breakpoint on <code class="language-plaintext highlighter-rouge">arr</code>. But we need to pause after free to do
that.</p>

<p>Maybe simpler: set a normal breakpoint at the line <em>after</em> the first
<code class="language-plaintext highlighter-rouge">free(arr)</code> in our code (i.e., at the <code class="language-plaintext highlighter-rouge">std::cout &lt;&lt; arr[0]</code> line). When
we hit that, <code class="language-plaintext highlighter-rouge">arr</code> is already freed, but we have its value. We can then
set a data breakpoint.</p>

<p><strong>Step 3:</strong> So set a breakpoint at the <code class="language-plaintext highlighter-rouge">std::cout &lt;&lt; ... arr[0] ...</code>
line (line 7). Start debugging. The program runs, frees arr (not caught
yet), and stops at line 7 due to our breakpoint. Now in the
<strong>Variables</strong> pane, we see <code class="language-plaintext highlighter-rouge">arr</code> and its value. Now right-click on <code class="language-plaintext highlighter-rouge">arr</code>
and choose <strong>“Break on Value Change”</strong> (this is the data breakpoint
feature)<a href="https://devblogs.microsoft.com/cppblog/whats-new-for-c-debugging-in-visual-studio-code/#:~:text=To%20set%20a%20data%20breakpoint,select%20Break%20on%20Value%20Change">[12]</a>.
However, “Break on Value Change” is intended to break when the <em>value of
a variable</em> changes, which isn’t exactly our scenario – we want to
break on access to the memory pointed by arr. The cpptools data
breakpoint actually sets a hardware watchpoint on that memory address
(it works for global/static variables or heap addresses, up to 4 or 8
bytes). If <code class="language-plaintext highlighter-rouge">arr</code> were global, it’d break when <code class="language-plaintext highlighter-rouge">arr</code> changes. But here,
we want to watch the pointed memory.</p>

<p>We might have to use the Debug Console with GDB commands: <code class="language-plaintext highlighter-rouge">watch *(arr)</code>
in gdb could watch the memory pointed by arr. Let’s do that: in Debug
Console, type:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>-exec watch *(int*)arr
</code></pre></div></div>

<p>GDB will set a watchpoint on that address. Now continue (F5). The
watchpoint should trigger immediately because we are about to read it
(actually, we’re at the line already, if we step or continue, it will
try to execute that read). If the breakpoint is set correctly, GDB will
break on the memory access. VS Code will indicate a break (maybe showing
the watchpoint in the Breakpoints pane as well).</p>

<p>Now we know the watchpoint hit, meaning an access to freed memory
happened. The output may not have even printed yet, and we caught it.</p>

<p><strong>Step 4:</strong> Continue after that, and the double free likely causes a
crash which GDB will catch as well (maybe an abort or another watchpoint
if we set one for free).</p>

<p>Admittedly, data breakpoints are a bit clunky in VS Code with GDB for
this scenario. Another approach: If using WSL or Linux environment, you
could use Valgrind or AddressSanitizer, but we’re focusing on the
debugger.</p>

<p><strong>Step 5:</strong> Summarize findings. The VS Code + GDB approach (cppdbg)
confirms the same problem through manual watchpoint usage. The senior
engineer notes that using the debugger, we intercepted the invalid
memory usage which otherwise might have gone unnoticed or only shown up
as a crash much later.</p>

<hr />

<p>In this case study, we demonstrated how to debug a tricky memory
corruption where the program’s failure isn’t immediate. <strong>Key
techniques:</strong> using breakpoints on library calls (like <code class="language-plaintext highlighter-rouge">free</code>), and
using <strong>watchpoints (data breakpoints) to catch any access to freed
memory</strong>. All debuggers – LLDB, WinDbg, GDB – have this
capability<a href="https://gist.github.com/rais38/6ecead686af9291da542#:~:text=Set%20a%20watchpoint%20on%20a,my_ptr">[5]</a><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-#:~:text=This%20example%20sets%20a%20conditional,the%20debugger%20should%20break%20in">[11]</a>.
In VS Code, the UI provides data breakpoints for certain scenarios, or
you can invoke them via the console. The thought process is: <em>“I suspect
a use-after-free; let’s catch the moment the freed memory is touched.”</em>
This way, we caught the bug in action. The root cause analysis is
straightforward once you see that: freeing memory and then using it is a
bug, as is freeing it twice.</p>

<p>Next, we’ll explore a different category of bug: <strong>stack overflow due to
recursion</strong>, to see how debuggers handle deep call stacks.</p>

<h2 id="case-study-3-stack-overflow-infinite-recursion">Case Study 3: Stack Overflow (Infinite Recursion)</h2>

<p><strong>The Bug:</strong> Our third scenario is a function that inadvertently calls
itself infinitely (a recursion bug), eventually causing a <strong>stack
overflow</strong> crash. This will test our debuggers’ ability to handle deep
call stacks. The code:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#include &lt;iostream&gt;

unsigned int fib(unsigned int n) {
    if (n == 0) return 0;
    if (n == 1) return 1;
    // Bug: wrong recursion, calls fib(n) instead of fib(n-2)
    return fib(n-1) + fib(n);
}

int main() {
    std::cout &lt;&lt; "fib(2) = " &lt;&lt; fib(2) &lt;&lt; std::endl;
    return 0;
}
</code></pre></div></div>

<p>This intends to compute Fibonacci numbers, but there’s a <strong>bug in the
recursion</strong>: the function calls <code class="language-plaintext highlighter-rouge">fib(n)</code> again instead of <code class="language-plaintext highlighter-rouge">fib(n-2)</code>. So
<code class="language-plaintext highlighter-rouge">fib(2)</code> calls <code class="language-plaintext highlighter-rouge">fib(1)</code> and <code class="language-plaintext highlighter-rouge">fib(2)</code> again, leading to an infinite
recursion. Eventually the program will crash with a stack overflow (when
the stack memory is exhausted). The behavior: it will likely print
nothing and then segfault with a stack overflow error.</p>

<h3 id="debugging-with-lldb-macos-2">Debugging with LLDB (macOS)</h3>

<p><strong>Step 1: Compile with -g.</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>clang++ -g -O0 -o fib_bug fib_bug.cpp
</code></pre></div></div>

<p><strong>Step 2: Run under LLDB.</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>lldb fib_bug
(lldb) run
</code></pre></div></div>

<p>This program will run and eventually crash. LLDB will stop the process
at the crash point. On macOS, a stack overflow typically appears as an
<strong>EXC_BAD_ACCESS</strong> (access violation) at some stack address or just an
abrupt stop. LLDB might say something like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Process 18200 stopped
* thread #1: tid 0x12345, 0x0000000100000e?? fib_bug`fib(n=2) + 87 at fib_bug.cpp:..., stop reason = EXC_BAD_ACCESS (code=2, address=0x7fff5fbfffc8)[3]
</code></pre></div></div>

<p>It shows we stopped in <code class="language-plaintext highlighter-rouge">fib(n=2)</code> with a bad access at some address near
the stack top (the address 0x7fff5fbfffc8 is likely near the end of
stack). This indicates a stack overflow.</p>

<p><strong>Step 3: Examine the stack trace.</strong> The big clue for a recursion bug is
in the backtrace. Type <code class="language-plaintext highlighter-rouge">bt</code> in LLDB:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) bt
* thread #1: stop reason = EXC_BAD_ACCESS
  * frame #0: 0x0000000100000add fib_bug`fib(n=2) + 61 at fib_bug.cpp:??
    frame #1: 0x0000000100000af7 fib_bug`fib(n=2) + 87 at fib_bug.cpp:??
    frame #2: 0x0000000100000af7 fib_bug`fib(n=2) + 87 at fib_bug.cpp:??
    frame #3: 0x0000000100000af7 fib_bug`fib(n=2) + 87 at fib_bug.cpp:??
    ... (many repeated frames) ...
    frame #50: 0x0000000100000af7 fib_bug`fib(n=2) + 87 at fib_bug.cpp:??
    frame #51: 0x0000000100000c9e fib_bug`main + 78 at fib_bug.cpp:12
</code></pre></div></div>

<p>LLDB will list a <strong>lot</strong> of frames (it might truncate after a large
number). We can see <code class="language-plaintext highlighter-rouge">fib(n=2)</code> repeated many
times<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=,fib%28n%3D2%29%20%2B%2061%20at%20lldbtutorial%3A18">[16]</a><a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=,%2B%2078%20at%20lldbtutorial%3A80">[17]</a>.
Frame #51 shows <code class="language-plaintext highlighter-rouge">main</code>. The repeated pattern indicates that <code class="language-plaintext highlighter-rouge">fib(2)</code> is
calling itself recursively and never stopping. The senior engineer
observes: <em>“The stack is filled with calls to fib(2). This must be
infinite recursion.”</em></p>

<p>We can scroll the stack (<code class="language-plaintext highlighter-rouge">bt</code> might show partial, but it’s enough to see
the pattern).</p>

<p><strong>Step 4: Inspect variables (if needed).</strong> We might inspect the value of
<code class="language-plaintext highlighter-rouge">n</code> in the top frame:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) frame variable n
(unsigned int) n = 2
</code></pre></div></div>

<p>It’s always 2 in these frames, meaning the function keeps recursing with
the same <code class="language-plaintext highlighter-rouge">n</code>. That confirms the bug: the code didn’t decrease <code class="language-plaintext highlighter-rouge">n</code>
properly in one branch. We might check one frame further down to see if
any difference, but likely all show n=2.</p>

<p><strong>Step 5: Breakpoints for insight (optional).</strong> Another debugging
approach: set a breakpoint at the start of <code class="language-plaintext highlighter-rouge">fib</code> and run, then observe
the flow. For example,</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) b fib
(lldb) run
</code></pre></div></div>

<p>Then manually step through a couple of calls with <code class="language-plaintext highlighter-rouge">n=2</code> to see what
happens. You’d see it call <code class="language-plaintext highlighter-rouge">fib(2)</code>, then inside call <code class="language-plaintext highlighter-rouge">fib(1)</code> and
<code class="language-plaintext highlighter-rouge">fib(2)</code> again, etc. After a few steps, the pattern becomes clear. In
practice, the backtrace from the crash gave it away directly.</p>

<p><strong>Step 6: Conclusion in LLDB.</strong> The program crashed due to stack
overflow (EXC_BAD_ACCESS on stack). The cause is the infinite recursion
(buggy <code class="language-plaintext highlighter-rouge">fib</code>). The fix is to change <code class="language-plaintext highlighter-rouge">fib(n)</code> to <code class="language-plaintext highlighter-rouge">fib(n-2)</code> in the
return. The senior engineer’s thought: <em>“We have a recursion that never
ends, causing a stack overflow. The debugger showed an endlessly
repeating call stack.”</em></p>

<h3 id="debugging-with-windbg-windows-2">Debugging with WinDbg (Windows)</h3>

<p>On Windows, an infinite recursion typically triggers a
<strong>StackOverflowException</strong> (exception code 0xC00000FD). WinDbg will
catch this when the stack is exhausted.</p>

<p><strong>Step 1: Compile with MSVC debug.</strong> (Or MinGW, but MSVC’s output might
give a clearer call stack). E.g.:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cl /Zi /Od fib_bug.cpp /Fe:fib_bug.exe
</code></pre></div></div>

<p><strong>Step 2: Launch in WinDbg.</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>windbg fib_bug.exe
</code></pre></div></div>

<p>Run (<code class="language-plaintext highlighter-rouge">g</code>). The program will run until the stack overflow occurs. WinDbg
will then break execution and output something like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(1234.5678): Stack overflow - code c00000fd (first chance)[18]
First chance exceptions are reported before any exception handling...
</code></pre></div></div>

<p>This indicates a stack overflow exception (code <code class="language-plaintext highlighter-rouge">0xc00000fd</code>). Since
it’s unhandled, a second chance will also occur, but WinDbg stops on
first chance by default here.</p>

<p><strong>Step 3: Get the stack trace.</strong> Use <code class="language-plaintext highlighter-rouge">k</code>. This stack will be huge.
WinDbg might not show all frames by default. It could show something
like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:000&gt; k
  *** Stack trace may be truncated, frame count 1024 ***
00 fib_bug!fib(unsigned int)+0x?? 
01 fib_bug!fib(unsigned int)+0x?? 
02 fib_bug!fib(unsigned int)+0x?? 
... (repeats many times) ...
nn fib_bug!fib(unsigned int)+0x?? 
nn+1 fib_bug!main+0x?? 
</code></pre></div></div>

<p>It might display the first few and last few frames, with “...”
indicating repetition. If WinDbg truncates, we can try <code class="language-plaintext highlighter-rouge">kc 100</code> to show
100 frames or so. But the pattern will be clear: multiple entries of
<code class="language-plaintext highlighter-rouge">fib_bug!fib</code>. We know it’s repetitive.</p>

<p>We can also use <code class="language-plaintext highlighter-rouge">!analyze -v</code> (a WinDbg extension) which might summarize
that there was a stack overflow and possibly show the last calls. But
the manual approach suffices.</p>

<p><strong>Step 4: Check a couple of frames to confirm parameter values.</strong> We can
try to look at the top of stack. But note: in a stack overflow, the
system might not be able to unwind all symbols properly. Still, if
symbols are there, WinDbg knows the function name.</p>

<p>We might do:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:000&gt; .frame 0 
0:000&gt; dv
</code></pre></div></div>

<p>However, in a stack overflow, <code class="language-plaintext highlighter-rouge">dv</code> might fail (“unable to enumerate
locals”) because of corruption or because it’s too deep. Alternatively,
we can inspect a register for the parameter. On x64 Windows, <code class="language-plaintext highlighter-rouge">n</code>
(unsigned int) would be passed in ECX for recursive calls. The register
state might be lost. But given the repetitive calls, it’s likely the
same scenario: n=2 throughout.</p>

<p><strong>Step 5: Analyze the problem.</strong> WinDbg clearly indicated a Stack
Overflow. The call stack shows recursive <code class="language-plaintext highlighter-rouge">fib</code>. The senior engineer
infers the recursion bug. The output of the program (if any) didn’t even
get to print because it overflowed before returning.</p>

<p><strong>Step 6: Alternative debug: set a breakpoint in fib and watch
recursion.</strong> We could have done:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:000&gt; bp fib_bug!fib
0:000&gt; g
</code></pre></div></div>

<p>It would break at the first call to <code class="language-plaintext highlighter-rouge">fib(2)</code>. Then we could use <code class="language-plaintext highlighter-rouge">t</code>
(trace) or <code class="language-plaintext highlighter-rouge">p</code> (step) to step through recursion, but given it’s
infinite, stepping would be laborious. Instead, after a few steps you’d
see the pattern of calls. The backtrace from the crash is usually
enough.</p>

<p>In summary, WinDbg confirms infinite recursion by the nature of the
exception and the repetitive call stack.</p>

<h3 id="debugging-with-vs-code--codelldb-macos-2">Debugging with VS Code + CodeLLDB (macOS)</h3>

<p><strong>Step 1:</strong> Compile with debug symbols (<code class="language-plaintext highlighter-rouge">-g</code>). Open in VS Code.</p>

<p><strong>Step 2:</strong> Set a breakpoint at the start of <code class="language-plaintext highlighter-rouge">fib</code> (line 5).</p>

<p><strong>Step 3:</strong> Run the debugger. It will hit <code class="language-plaintext highlighter-rouge">fib(2)</code> at the beginning. You
can inspect <code class="language-plaintext highlighter-rouge">n</code> (it’s 2). Step into the recursion: - Step over the
<code class="language-plaintext highlighter-rouge">if (n==0)</code> and <code class="language-plaintext highlighter-rouge">if (n==1)</code> conditions until the return. - Step into the
<code class="language-plaintext highlighter-rouge">return fib(n-1) + fib(n)</code> expression. VS Code will go into the next
call of <code class="language-plaintext highlighter-rouge">fib</code>. Now you’re in <code class="language-plaintext highlighter-rouge">fib</code> again with <code class="language-plaintext highlighter-rouge">n=1</code> (for the <code class="language-plaintext highlighter-rouge">fib(n-1)</code>
part). Step through that – it will eventually return 1. - Then it will
call <code class="language-plaintext highlighter-rouge">fib(n)</code> where n is still 2 for the second part of the addition.
Now you’re calling <code class="language-plaintext highlighter-rouge">fib(2)</code> again, starting the cycle anew.</p>

<p>You’ll notice the debugger hitting the breakpoint in <code class="language-plaintext highlighter-rouge">fib</code> repeatedly.
The <strong>Call Stack</strong> pane in VS Code will start showing multiple <code class="language-plaintext highlighter-rouge">fib</code>
frames one under another as you step deeper. Eventually, if you just
continue (F5) without breakpoints, the program will run until it
overflows. VS Code will then stop with a message (it might say “Program
received signal SIGSEGV” or just exit unexpectedly). If CodeLLDB catches
it, you might not get a nice message like WinDbg’s, but you’ll know
something went wrong (process exited with code 11, etc.).</p>

<p>However, an interactive way: after noticing the repeat, you would deduce
the recursion bug and stop. You might not let it overflow fully since
the pattern is obvious. But if you did, CodeLLDB would break on the
segfault. The Variables and Call Stack at that moment would be similar
to LLDB’s view (lots of frames of <code class="language-plaintext highlighter-rouge">fib</code>). You can scroll in the Call
Stack panel to see the repeating pattern.</p>

<p><strong>Step 4:</strong> Analyze and conclude. The VS Code debugger reveals the
infinite recursion by the repeating calls. The fix is apparent once you
inspect the code logic.</p>

<h3 id="debugging-with-vs-code--cppdbg-windows-1">Debugging with VS Code + CppDbg (Windows)</h3>

<p><strong>Step 1:</strong> Compile with MinGW <code class="language-plaintext highlighter-rouge">-g</code>. In VS Code, set up GDB.</p>

<p><strong>Step 2:</strong> We can attempt the same approach: set a breakpoint in <code class="language-plaintext highlighter-rouge">fib</code>
and debug. The GDB backend will catch it similarly. If we let it run to
crash, GDB will stop with something like “Program received signal
SIGSEGV” when the stack overflows (GCC doesn’t throw a structured
exception; it’ll just segfault on overflow). The call stack in VS Code
will show many <code class="language-plaintext highlighter-rouge">fib</code> frames.</p>

<p><strong>Step 3:</strong> We inspect the call stack in VS Code. The UI might not list
all thousands of frames, but it will list as many as it can, showing
<code class="language-plaintext highlighter-rouge">fib</code> repeated and eventually main at the bottom. That’s evidence
enough.</p>

<p><strong>Step 4:</strong> The analysis is the same: stack overflow due to runaway
recursion.</p>

<hr />

<p>In this case study, the <strong>transferable techniques</strong> are: using the
debugger to catch a crash due to stack overflow and using the backtrace
to identify a repeating pattern of calls. All tools gave us a clue: -
LLDB showed repeated <code class="language-plaintext highlighter-rouge">fib(n=2)</code>
frames<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=,fib%28n%3D2%29%20%2B%2061%20at%20lldbtutorial%3A18">[16]</a>. -
WinDbg explicitly flagged a stack overflow
exception<a href="https://stackoverflow.com/questions/18721841/how-to-find-the-source-of-a-stackoverflowexception-in-my-application#:~:text=that%20raised%20the%20exception%2C%20and,will%20be%20something%20like%20this">[18]</a>. -
The VS Code debug views also showed many repeated calls.</p>

<p>The senior engineer’s process is to recognize that pattern as a logical
bug (incorrect recursion stopping condition). No fancy watchpoints
needed here, just careful reading of the stack trace.</p>

<h2 id="case-study-4-data-race-and-multithreading-bug-concurrent-access">Case Study 4: Data Race and Multithreading Bug (Concurrent Access)</h2>

<p><strong>The Bug:</strong> Our final example involves threads. We have two threads
accessing a shared pointer without proper synchronization. This can lead
to a <em>race condition</em>, where one thread frees memory while another
thread is still using it. This is a classic multi-threaded bug that can
cause crashes or unpredictable results depending on timing.</p>

<p>Consider:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#include &lt;thread&gt;
#include &lt;chrono&gt;
#include &lt;iostream&gt;

int *sharedPtr = nullptr;

void writer() {
    sharedPtr = new int(42);
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
    // Free the memory and set pointer to null
    delete sharedPtr;
    sharedPtr = nullptr;
}

void reader() {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    // Attempt to use sharedPtr after it may have been freed
    if (sharedPtr) { 
        *sharedPtr = 10;  // BUG: possible use-after-free if writer freed it
    }
}

int main() {
    std::thread t1(writer);
    std::thread t2(reader);
    t1.join();
    t2.join();
    return 0;
}
</code></pre></div></div>

<p>In this code, the <strong>writer thread</strong> allocates an int and after 50ms
deletes it and sets <code class="language-plaintext highlighter-rouge">sharedPtr</code> to null. The <strong>reader thread</strong> waits
100ms (ensuring writer has likely freed the memory) and then checks
<code class="language-plaintext highlighter-rouge">sharedPtr</code> and if not null, writes to it. The intention might have been
to read something, but here we simulate a write. There’s a race:
depending on timing, <code class="language-plaintext highlighter-rouge">sharedPtr</code> could be non-null when checked (if
reader’s 100ms sleep isn’t long enough or if writer was slower), or it
could already be null.</p>

<ul>
  <li>If <code class="language-plaintext highlighter-rouge">sharedPtr</code> is null, the <code class="language-plaintext highlighter-rouge">if</code> will skip and nothing happens (no
crash).</li>
  <li>If <code class="language-plaintext highlighter-rouge">sharedPtr</code> is non-null (i.e., the writer hasn’t nullified it yet
or hasn’t run delete yet, which is unlikely with these timings), then
no issue (the write happens before deletion).</li>
  <li>The worst case is if writer deletes and sets it to null exactly
between the if-check and the write in reader – that’s a tiny window.
In our example, we set <code class="language-plaintext highlighter-rouge">sharedPtr = nullptr</code> in writer, so reader will
likely see null and do nothing. But imagine if we <em>didn’t</em> set it to
nullptr in writer after delete (a more common bug scenario), then
reader would definitely attempt to write freed memory.</li>
</ul>

<p>Let’s tweak for a more demonstrable crash: say the writer <strong>does not</strong>
set it to nullptr after delete (simulate forgetting to clear the
pointer):</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>// ... in writer()
delete sharedPtr;
// sharedPtr not cleared here, still points to freed memory
</code></pre></div></div>

<p>Now the reader will find <code class="language-plaintext highlighter-rouge">sharedPtr</code> still pointing to something
(dangling) and try <code class="language-plaintext highlighter-rouge">*sharedPtr = 10</code>, which is a use-after-free. This
likely causes a crash. We’ll debug that scenario. (The original code
with setting to nullptr actually turns the bug into a null-dereference
if the reader thread runs late, which would also crash at
<code class="language-plaintext highlighter-rouge">*sharedPtr = 10</code> since sharedPtr is null. That’s equally illustrative.)</p>

<p>So either we debug a <em>dangling pointer race</em> or a <em>null pointer race</em>.
Both are results of a race condition. We expect an access violation in
the reader thread.</p>

<p>This is a multi-thread bug, so we’ll see how to inspect thread states
and coordinate breakpoints.</p>

<h3 id="debugging-with-lldb-macos-3">Debugging with LLDB (macOS)</h3>

<p><strong>Step 1: Compile with -g (and consider</strong> <code class="language-plaintext highlighter-rouge">-fsanitize=thread</code> <strong>if we
wanted TSAN, but here we stick to manual debugging).</strong></p>

<p><strong>Step 2: Run under LLDB.</strong></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>lldb race_bug
(lldb) run
</code></pre></div></div>

<p>The program might or might not crash every time, depending on
scheduling. With the timing we gave (writer frees at 50ms, reader writes
at 100ms), the reader will likely crash because by 100ms the pointer was
freed and left dangling (not null). So assume it crashes. LLDB will stop
with an access violation in the reader thread.</p>

<p>It might show something like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Process 18300 stopped
* thread #2, stop reason = EXC_BAD_ACCESS (code=1, address=0xXXXXXXXX)
    frame #0: 0x0000000100001040 race_bug`reader() + 32 at race_bug.cpp:16
   14    std::this_thread::sleep_for(std::chrono::milliseconds(100));
   15    // Attempt to use sharedPtr after free
-&gt; 16    *sharedPtr = 10;  // crash here
   17 }
</code></pre></div></div>

<p>This indicates <strong>thread #2</strong> (likely the reader thread) crashed trying
to write to an invalid
address<a href="https://levelblue.com/blogs/spiderlabs-blog/windows-debugging-exploiting-part-3-windbg-time-travel-debugging#:~:text=%281f20.fc0%29%3A%20Access%20violation%20,first%2Fsecond%20chance%20not%20available">[19]</a>.
The address might be some freed heap address. We see the source line.</p>

<p><strong>Step 3: Examine threads.</strong> We have multiple threads. In LLDB, use
<code class="language-plaintext highlighter-rouge">thread list</code> to list threads:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) thread list
Process 18300 stopped
* thread #1: tid = 0x1234, 0x... race_bug`writer()  (running or finished)
* thread #2: tid = 0x1235, 0x... race_bug`reader()  stop reason = EXC_BAD_ACCESS
</code></pre></div></div>

<p>It shows thread #2 stopped due to the exception. Thread #1 might have
finished (or maybe still in join). We can switch to thread 1 to see its
state:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) thread select 1
(lldb) bt
</code></pre></div></div>

<p>If writer thread finished and is waiting in join or ended, the backtrace
might show it in <code class="language-plaintext highlighter-rouge">pthread_join</code> or somewhere, or nothing if it’s
terminated. If it’s still joining, frame might be in <code class="language-plaintext highlighter-rouge">main</code> at join
call.</p>

<p>Anyway, the main issue is with thread #2. We can inspect <code class="language-plaintext highlighter-rouge">sharedPtr</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) frame variable sharedPtr
(int *) sharedPtr = 0xXXXXXXXX
</code></pre></div></div>

<p>It will show a dangling address (the one freed). Possibly if guard
malloc is on, accessing it triggers crash. We know it’s invalid.</p>

<p><strong>Step 4: Use watchpoints to catch the race proactively.</strong> Another
approach the senior engineer might use: set a watchpoint on <code class="language-plaintext highlighter-rouge">sharedPtr</code>
(the global pointer) to see when it changes or when it’s accessed. For
instance, before running, in LLDB:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) watchpoint set variable sharedPtr
</code></pre></div></div>

<p>This will break whenever <code class="language-plaintext highlighter-rouge">sharedPtr</code> is written (by default, watchpoints
monitor writes). So as soon as writer does <code class="language-plaintext highlighter-rouge">sharedPtr = new int(42)</code> or
later <code class="language-plaintext highlighter-rouge">sharedPtr = nullptr</code>, LLDB will break. This might be a bit too
many breaks, but let’s say we did that.</p>

<ul>
  <li>It breaks when writer thread writes to <code class="language-plaintext highlighter-rouge">sharedPtr</code> (setting it to new
int). We continue.</li>
  <li>It breaks again when writer sets <code class="language-plaintext highlighter-rouge">sharedPtr = nullptr</code> after delete.
We continue.</li>
  <li>Now, crucially, we could also watch memory at the allocated int
address to catch use after free. But since we now know the crash
happens, it’s okay.</li>
</ul>

<p><strong>Step 5: Multi-thread inspection.</strong> We might want to see what happened
in thread scheduling. We know thread1 freed and nullified the pointer at
t=50ms. Thread2 attempted use at t=100ms. Actually in this scenario with
nullification, thread2 would crash on null deref. In the scenario
without nullification, thread2 crashed on dangling pointer. In any case,
the debugger caught it.</p>

<p>LLDB can also show thread states: <code class="language-plaintext highlighter-rouge">thread list</code> we did, and <code class="language-plaintext highlighter-rouge">bt all</code> can
show backtrace for all threads. If we do <code class="language-plaintext highlighter-rouge">bt all</code>, we might see:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(lldb) bt all
* thread #2: ... reader() frame 0 at race_bug.cpp:16 stop reason=EXC_BAD_ACCESS
  thread #1: ... main() frame 0 at race_bug.cpp:... (probably in join or after)
</code></pre></div></div>

<p>So we confirm thread2 died in <code class="language-plaintext highlighter-rouge">reader()</code>.</p>

<p><strong>Step 6: Conclusion from LLDB.</strong> The senior engineer sees that the
reader thread crashed trying to access <code class="language-plaintext highlighter-rouge">sharedPtr</code>. The value was
already freed by writer. The root cause is a race: no synchronization,
leading to use-after-free across threads. The fix is to protect
sharedPtr with locks or use atomic operations or join timing such that
reader doesn’t run after free.</p>

<h3 id="debugging-with-windbg-windows-3">Debugging with WinDbg (Windows)</h3>

<p>In WinDbg, multi-thread debugging means we have to pay attention to
thread context.</p>

<p><strong>Step 1: Compile for Windows.</strong> e.g. MSVC with /Zi.</p>

<p><strong>Step 2: Launch WinDbg and run.</strong> The program might crash similarly
with an access violation in one of the threads. WinDbg will break and
show something like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(1db4.3f48): Access violation - code c0000005 (first chance)
</code></pre></div></div>

<p>We need to see which thread crashed. WinDbg’s default thread is the one
that hit the exception. Use <code class="language-plaintext highlighter-rouge">~</code> to list threads:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:002&gt; ~
   0  Id: 1db4.3f48 Suspend: 0 Teb: ... Unfrozen (this might be thread 0)
   1  Id: 1db4.5c70 Suspend: 0 Teb: ... Unfrozen 
.  2  Id: 1db4.4a88 Suspend: 0 Teb: ... Unfrozen  &lt;-- the dot indicates current thread (#2)
</code></pre></div></div>

<p>Thread 2 is current (the one with the exception). Let’s see its stack:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:002&gt; k
 # Child-SP     RetAddr      Call Site
00 002ff5c0     01101567     race_bug!reader(void)+0x27 [race_bug.cpp @ 16]
01 002ff5d0     75c4f5f8     race_bug!invoke_thread_procedure+0x...   // thread startup internals
02 002ff60c     77a25efa     KERNEL32!BaseThreadInitThunk+0x18
03 002ff61c     77a25ec8     ntdll!RtlUserThreadStart+0x2a
</code></pre></div></div>

<p>Frame 0 is <code class="language-plaintext highlighter-rouge">reader()</code> at line 16, offset 0x27 (likely at
<code class="language-plaintext highlighter-rouge">*sharedPtr = 10</code>). So thread 2 (ID 4a88) crashed there.</p>

<p>Switch to thread 1 if needed:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0:002&gt; ~1s
1:001&gt; k
 # Child-SP     RetAddr      Call Site
00 00aff7c4     77a8b4a2     ntdll!NtWaitForSingleObject+0x12
01 00aff83c     75c4fa29     KERNEL32!WaitForSingleObjectEx+0x92
02 00aff858     75c4f9e8     KERNEL32!WaitForSingleObject+0x12
03 00aff874     0110148a     race_bug!std::this_thread::sleep_for&lt;...&gt; // maybe writer sleeping or join
...
</code></pre></div></div>

<p>Thread 1 might be writer or main waiting. Possibly thread 1 is main
waiting for join, and writer might have been thread 0 or vice versa. We
can identify by looking at code context if symbols allow.</p>

<p>Anyway, to keep it simple: the thread that crashed is the reader thread.
We see it clearly in the call stack.</p>

<p><strong>Step 3: Inspect variables.</strong> We know <code class="language-plaintext highlighter-rouge">sharedPtr</code> is global. We can try
to evaluate it:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>2:002&gt; dx sharedPtr
sharedPtr : 0x00ab1230  (int*)    ; or use ? sharedPtr
</code></pre></div></div>

<p>It shows some address. That’s the freed address presumably. If we have
debug heap, maybe it’s overwritten. But anyway.</p>

<p>Alternatively, since reader had a parameter or local? Actually
<code class="language-plaintext highlighter-rouge">reader()</code> has no args. The pointer is global, so we just had to inspect
global.</p>

<p><strong>Step 4: Use WinDbg breakpoints/watchpoints.</strong> Another approach: set a
breakpoint on <code class="language-plaintext highlighter-rouge">reader</code> or on the line of <code class="language-plaintext highlighter-rouge">*sharedPtr = 10</code> to catch it
before crash. E.g., use <code class="language-plaintext highlighter-rouge">.printf</code> or <code class="language-plaintext highlighter-rouge">bu race_bug!reader+0x27</code> (if we
compute offset) – but better is to use a <strong>conditional breakpoint or
guard</strong>: In WinDbg, you could do a memory breakpoint on the pointer
address if you knew it, but that’s tricky since pointer value changes at
runtime.</p>

<p>Alternatively, set a breakpoint on <code class="language-plaintext highlighter-rouge">delete sharedPtr</code> in writer thread,
then step to see what happens and quickly switch to reader thread.
That’s complicated.</p>

<p>However, WinDbg has a nice feature: <strong>Stop on exceptions</strong>. We can
configure to break on access violation as soon as it happens (first
chance). It already does first chance break by default. So we got it at
the moment of fault.</p>

<p><strong>Step 5: Synchronization debugging tools:</strong> If the bug was subtler (not
always crashing), one might use tools like Application Verifier or Intel
Inspector or ThreadSanitizer. But with pure WinDbg, we rely on catching
the crash or manual inspection with breakpoints.</p>

<p>We have enough with the crash caught.</p>

<p><strong>Step 6: Conclusion from WinDbg.</strong> We identified the crashing thread
and location. The fix is to add synchronization. The senior engineer’s
reasoning: <em>“The reader thread accessed memory that the writer thread
freed. This is a race condition.”</em> We saw this because the crash
happened in the reader, and we know writer did a delete earlier. So the
remedy is to ensure proper ordering or locking.</p>

<h3 id="debugging-with-vs-code--codelldb-macos-3">Debugging with VS Code + CodeLLDB (macOS)</h3>

<p><strong>Step 1:</strong> Compile with -g, open in VS Code.</p>

<p><strong>Step 2:</strong> Set breakpoints or let it run. Multi-thread debugging in VS
Code: If we run without breakpoints, the program may crash. VS Code will
break on the crash (SIGSEGV). We’ll then need to inspect threads.</p>

<p>So perhaps set a breakpoint at the problematic line in <code class="language-plaintext highlighter-rouge">reader</code>
(<code class="language-plaintext highlighter-rouge">*sharedPtr = 10</code>). Run the debugger. Possibly the writer thread runs
and frees before reader hits that line, but since we have a breakpoint
at that line, when the reader thread is about to execute it, it will
pause <em>before</em> actually doing it. This is great – we catch it right in
time. The program will freeze when thread 2 reaches that line, while
thread 1 might have already done its job.</p>

<p>VS Code will show we are paused at line 16 (inside reader). In the call
stack, it will show that this pause is in thread 2 (it usually labels
threads like Thread (tid:0x..)). We can use the threads dropdown in VS
Code’s debug toolbar to switch between threads. We might see Thread 1 in
some other location (maybe finished or in join).</p>

<p><strong>Step 3:</strong> Check the value of <code class="language-plaintext highlighter-rouge">sharedPtr</code> now. In the Variables pane,
since <code class="language-plaintext highlighter-rouge">sharedPtr</code> is global, it might appear under “Globals” or we can
evaluate it in the Debug Console: <code class="language-plaintext highlighter-rouge">print sharedPtr</code>. It likely shows
<code class="language-plaintext highlighter-rouge">0x...</code> (some address). Is it null or an address? If writer set it to
nullptr already, it will show 0x0. If we simulate the scenario where
writer didn’t null it, it shows a non-null address that’s actually
freed. Either way, it’s not a valid allocated memory. If it’s 0, that
means the code is about to dereference a null – a guaranteed crash. If
it’s a dangling address, also a crash.</p>

<p>Now we know if we continue, it will crash. But we have essentially
caught the bug in the act (the breakpoint sort of acted like a
watchpoint on that code line).</p>

<p><strong>Step 4:</strong> We can inspect thread 1 as well. Switch to thread 1 in VS
Code’s thread picker. Maybe it’s at <code class="language-plaintext highlighter-rouge">delete sharedPtr;</code> or past it. If
writer hasn’t finished, maybe it’s sleeping or just did delete and about
to set null (if that code existed). Possibly thread 1 is already done
and waiting in join in main. Either way, nothing more needed from it.</p>

<p><strong>Step 5:</strong> We know the issue now: at this breakpoint, <code class="language-plaintext highlighter-rouge">sharedPtr</code> was
freed. If it’s null, the code is about to do <code class="language-plaintext highlighter-rouge">*0 = 10</code>. If it’s not null
(dangling), it’s even more insidious because the <code class="language-plaintext highlighter-rouge">if(sharedPtr)</code> check
passes and we attempt to write an invalid location. In either case, we
have a bug.</p>

<p><strong>Step 6:</strong> If we hit continue, we expect a crash. VS Code would then
stop the program with a SIGSEGV notice.</p>

<p><strong>Step 7:</strong> Data breakpoint method: Alternatively, we could have tried
using the data breakpoint feature on <code class="language-plaintext highlighter-rouge">sharedPtr</code>. In VS Code, we could
right-click <code class="language-plaintext highlighter-rouge">sharedPtr</code> in the Variables pane and "Break on Value
Change". That would break when writer thread changes <code class="language-plaintext highlighter-rouge">sharedPtr</code> (on
allocation or deletion). That might help us see the timing. For
instance, break when <code class="language-plaintext highlighter-rouge">sharedPtr</code> becomes null. Then resume and then
break in reader. This is a bit advanced, but doable. It would show the
interleaving of operations.</p>

<p><strong>Step 8:</strong> Conclusion for VS Code + CodeLLDB. We effectively identified
the race by catching one thread at the point of misuse. The solution is
to synchronize access to <code class="language-plaintext highlighter-rouge">sharedPtr</code> (e.g., join threads in proper order
or use a mutex or atomic).</p>

<h3 id="debugging-with-vs-code--cppdbg-windows-2">Debugging with VS Code + CppDbg (Windows)</h3>

<p>Similarly, with VS Code and GDB or the Visual Studio debug engine: - We
can set a breakpoint at the write line in reader. Run, it pauses in
thread 2. We inspect the pointer. See it’s invalid. - Or let it crash
and then inspect threads.</p>

<p>Using the MSVC debugger in VS Code (cppvsdbg) would give similar info:
it would break on the exception and you could see the thread and call
stack.</p>

<p>One helpful UI feature: VS Code shows a <strong>Threads</strong> view where each
thread can be selected, and you can see where each thread is stopped.
This is useful to verify thread 1 maybe completed, thread 2 is at crash.</p>

<p>In GDB, if you want to catch the race earlier, you might use a
conditional breakpoint or watchpoint as earlier cases.</p>

<p>Anyway, the process is analogous.</p>

<hr />

<p>In this multi-thread case, the <strong>key techniques</strong> are: understanding
thread scheduling, using breakpoints to pause one thread, using
thread-specific commands to examine each thread’s stack (<code class="language-plaintext highlighter-rouge">thread list</code>
in lldb, <code class="language-plaintext highlighter-rouge">~</code> in WinDbg, thread dropdown in VS Code), and using
watchpoints or break-on-value-change to monitor shared variables across
threads<a href="https://devblogs.microsoft.com/cppblog/whats-new-for-c-debugging-in-visual-studio-code/#:~:text=To%20set%20a%20data%20breakpoint,select%20Break%20on%20Value%20Change">[12]</a>.
The senior engineer tracks the sequence of events: writer did X, reader
did Y, leading to crash.</p>

<p>By seeing that the crash happened in reader and knowing writer freed
memory earlier, we pinpoint the race condition. This is a transferable
approach: when debugging a multithreading bug, always identify which
thread crashed and what the other threads were doing.</p>

<h2 id="conclusion-and-key-takeaways">Conclusion and Key Takeaways</h2>

<p>We’ve walked through four debugging scenarios (null pointer,
use-after-free, stack overflow, and a multithreaded race) using four
different tools. Despite the differences in interface, the <strong>core
debugging steps</strong> are consistent:</p>

<ul>
  <li><strong>Compile with debugging symbols</strong> to get meaningful
information<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=match%20at%20L204%20The%20compiler,as%20opposed%20to%20deployment">[1]</a>.
(e.g., <code class="language-plaintext highlighter-rouge">-g</code> for GCC/Clang, <code class="language-plaintext highlighter-rouge">/Zi</code> for MSVC).</li>
  <li><strong>Run the program under the debugger</strong> and reproduce the issue (crash
or misbehavior).</li>
  <li><strong>Set breakpoints</strong> at strategic locations (at the crash line, or
before the bug triggers) to pause execution and inspect state.</li>
  <li><strong>Use the call stack (backtrace)</strong> to see the chain of function calls
leading to the bug. This often reveals infinite recursions or who
called the faulty
function<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=,fib%28n%3D2%29%20%2B%2061%20at%20lldbtutorial%3A18">[16]</a>.</li>
  <li><strong>Inspect variables and memory</strong> at the point of failure. Check
pointer values, indices, etc. All debuggers let you examine variables
(<code class="language-plaintext highlighter-rouge">frame var</code>/<code class="language-plaintext highlighter-rouge">print</code> in LLDB, <code class="language-plaintext highlighter-rouge">dv</code>/<code class="language-plaintext highlighter-rouge">?</code> in WinDbg, the Variables pane
or <code class="language-plaintext highlighter-rouge">print</code> in VS Code).</li>
  <li><strong>Use watchpoints (data breakpoints) for memory issues</strong> to catch when
a variable changes or when freed memory is
accessed<a href="https://gist.github.com/rais38/6ecead686af9291da542#:~:text=Set%20a%20watchpoint%20on%20a,my_ptr">[5]</a><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-#:~:text=This%20example%20sets%20a%20conditional,the%20debugger%20should%20break%20in">[11]</a>.
We saw this was invaluable for use-after-free bugs.</li>
  <li><strong>Consider thread interactions</strong> in multi-threaded programs. Check the
state of each thread (using thread lists or VS Code's thread view),
and use breakpoints to freeze threads at critical moments. We
essentially performed <em>post-mortem</em> analysis on the crashing thread
and <em>live analysis</em> by pausing threads.</li>
  <li><strong>Interpret the debugger output</strong>: For example, an <strong>EXC_BAD_ACCESS /
c0000005</strong> means invalid memory access – likely null deref or freed
memory access. A <strong>c00000fd</strong> means stack
overflow<a href="https://stackoverflow.com/questions/18721841/how-to-find-the-source-of-a-stackoverflowexception-in-my-application#:~:text=that%20raised%20the%20exception%2C%20and,will%20be%20something%20like%20this">[18]</a>.
These codes and messages point to categories of bugs.</li>
</ul>

<p>The senior engineer’s thought process at each step is to formulate
hypotheses (“It might be a null pointer...”, “Maybe it’s recursing
infinitely...”, “Could this be a race condition?”) and then use the
debugger’s features to confirm or refute those hypotheses. By setting
breakpoints or watchpoints and examining program state, we gather
evidence for the root cause.</p>

<p>For each tool:\</p>
<ul>
  <li><strong>LLDB (macOS)</strong> – we used commands like <code class="language-plaintext highlighter-rouge">run</code>, <code class="language-plaintext highlighter-rouge">bt</code>, <code class="language-plaintext highlighter-rouge">print</code>,
<code class="language-plaintext highlighter-rouge">watchpoint set</code>, etc., to diagnose issues. LLDB gave us rich info like
function names and line numbers where things went
wrong<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=,fib%28n%3D2%29%20%2B%2071%20at">[4]</a>.\</li>
  <li><strong>WinDbg (Windows)</strong> – we learned to use <code class="language-plaintext highlighter-rouge">g</code>, <code class="language-plaintext highlighter-rouge">k</code>, <code class="language-plaintext highlighter-rouge">dv</code>, and thread
commands. It gave explicit exception codes (0xC0000005, 0xC00000FD)
which are clues, and its <code class="language-plaintext highlighter-rouge">ba</code> command allowed catching memory
accesses<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-#:~:text=Option%20Action">[10]</a>.
WinDbg is powerful for low-level analysis (like viewing heap state or
using <code class="language-plaintext highlighter-rouge">!analyze</code>), but even basic use helped us pinpoint the problem.\</li>
  <li><strong>VS Code with CodeLLDB</strong> – provided a user-friendly way to set
breakpoints and inspect variables in a GUI. We saw how to set function
breakpoints and that we could drop into the LLDB console for advanced
commands. It’s a great way to leverage LLDB with an IDE feel.\</li>
  <li><strong>VS Code with CppDbg (GDB)</strong> – similarly, we used breakpoints and
the Variables/Call Stack panes. We also noted VS Code’s <strong>“Break on
Value Change”</strong> feature for data
breakpoints<a href="https://devblogs.microsoft.com/cppblog/whats-new-for-c-debugging-in-visual-studio-code/#:~:text=To%20set%20a%20data%20breakpoint,select%20Break%20on%20Value%20Change">[12]</a>.
GDB’s behavior was comparable to LLDB’s in these cases.</li>
</ul>

<p>In practice, the choice of tool might depend on your environment (Visual
Studio has its own debugger, etc.), but the skills transfer. Setting
breakpoints, understanding memory addresses, interpreting call stacks –
these are universal debugging skills.</p>

<p><strong>Final advice for junior developers:</strong> Don’t be intimidated by memory
bugs. Use your debugger as a flashlight: - If you get a crash, run under
a debugger and let it tell you <em>where</em> and <em>why</em> (e.g., null pointer at
this line). - If the program doesn’t crash but behaves strangely (like
the use-after-free example that printed stale data), set traps
(watchpoints, breakpoints) at points where you suspect the bug (like
right after free, check if that memory gets touched). - For
multi-threaded issues, try to reproduce the issue with a debugger
attached, and inspect each thread’s state to piece together the
timeline.</p>

<p>Each of the case studies showed a slightly different use of the tools,
but the underlying approach is systematic: <strong>break, inspect, deduce,
confirm</strong>. With these techniques, you can tackle many C++ bugs involving
memory and concurrency. Happy debugging!</p>

<p><strong>Sources:</strong></p>

<ul>
  <li>Low-level debugger usage and watchpoint
commands<a href="https://gist.github.com/rais38/6ecead686af9291da542#:~:text=Set%20a%20watchpoint%20on%20a,my_ptr">[5]</a><a href="https://gist.github.com/rais38/6ecead686af9291da542#:~:text=...%20%28lldb%29%20bt%20,int32_t%29%20global%20%3D%205">[14]</a><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-#:~:text=This%20example%20sets%20a%20conditional,the%20debugger%20should%20break%20in">[11]</a></li>
  <li>LLDB debugging example of a crash and
backtrace<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=match%20at%20L238%20,fib%28n%3D2%29%20%2B%2071%20at">[3]</a><a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=,fib%28n%3D2%29%20%2B%2061%20at%20lldbtutorial%3A18">[16]</a></li>
  <li>Microsoft documentation on data breakpoints in VS
Code<a href="https://devblogs.microsoft.com/cppblog/whats-new-for-c-debugging-in-visual-studio-code/#:~:text=To%20set%20a%20data%20breakpoint,select%20Break%20on%20Value%20Change">[12]</a></li>
  <li>WinDbg output for stack overflow and access
violation<a href="https://stackoverflow.com/questions/18721841/how-to-find-the-source-of-a-stackoverflowexception-in-my-application#:~:text=that%20raised%20the%20exception%2C%20and,will%20be%20something%20like%20this">[18]</a><a href="https://levelblue.com/blogs/spiderlabs-blog/windows-debugging-exploiting-part-3-windbg-time-travel-debugging#:~:text=%281f20.fc0%29%3A%20Access%20violation%20,first%2Fsecond%20chance%20not%20available">[19]</a></li>
</ul>

<hr />

<p><a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=match%20at%20L204%20The%20compiler,as%20opposed%20to%20deployment">[1]</a>
<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=,lldb">[2]</a>
<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=match%20at%20L238%20,fib%28n%3D2%29%20%2B%2071%20at">[3]</a>
<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=,fib%28n%3D2%29%20%2B%2071%20at">[4]</a>
<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=,fib%28n%3D2%29%20%2B%2061%20at%20lldbtutorial%3A18">[16]</a>
<a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html#:~:text=,%2B%2078%20at%20lldbtutorial%3A80">[17]</a>
LLDB Tutorial</p>

<p><a href="https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html">https://klasses.cs.uchicago.edu/archive/2016/spring/15200-1/assigns/week5/lldb.html</a></p>

<p><a href="https://gist.github.com/rais38/6ecead686af9291da542#:~:text=Set%20a%20watchpoint%20on%20a,my_ptr">[5]</a>
<a href="https://gist.github.com/rais38/6ecead686af9291da542#:~:text=Set%20a%20watchpoint%20on%20a,a%20condition%20on%20a%20watchpoint">[13]</a>
<a href="https://gist.github.com/rais38/6ecead686af9291da542#:~:text=...%20%28lldb%29%20bt%20,int32_t%29%20global%20%3D%205">[14]</a>
Watchpoint in LLDB · GitHub</p>

<p><a href="https://gist.github.com/rais38/6ecead686af9291da542">https://gist.github.com/rais38/6ecead686af9291da542</a></p>

<p><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/getting-started-with-windbg#:~:text=3,readable%20function%20and%20variable%20names">[6]</a>
<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/getting-started-with-windbg#:~:text=Then%2C%20enter%20this%20command%3A">[7]</a>
Get Started with WinDbg User-Mode Debugger - Windows drivers |
Microsoft Learn</p>

<p><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/getting-started-with-windbg">https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/getting-started-with-windbg</a></p>

<p><a href="https://levelblue.com/blogs/spiderlabs-blog/windows-debugging-exploiting-part-3-windbg-time-travel-debugging#:~:text=0%3A000,first%2Fsecond%20chance%20not%20available">[8]</a>
<a href="https://levelblue.com/blogs/spiderlabs-blog/windows-debugging-exploiting-part-3-windbg-time-travel-debugging#:~:text=%281f20.fc0%29%3A%20Access%20violation%20,first%2Fsecond%20chance%20not%20available">[19]</a>
Windows Debugging &amp; Exploiting Part 3: WinDBG Time Travel Debugging</p>

<p><a href="https://levelblue.com/blogs/spiderlabs-blog/windows-debugging-exploiting-part-3-windbg-time-travel-debugging">https://levelblue.com/blogs/spiderlabs-blog/windows-debugging-exploiting-part-3-windbg-time-travel-debugging</a></p>

<p><a href="https://medium.com/ax1al/introduction-to-windbg-1177487c77a4#:~:text=Medium%20medium,the%20type%20of%20the">[9]</a>
Quick introduction to WinDbg. Reverse Engineering Tutorial - Medium</p>

<p><a href="https://medium.com/ax1al/introduction-to-windbg-1177487c77a4">https://medium.com/ax1al/introduction-to-windbg-1177487c77a4</a></p>

<p><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-#:~:text=Option%20Action">[10]</a>
<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-#:~:text=This%20example%20sets%20a%20conditional,the%20debugger%20should%20break%20in">[11]</a>
<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-#:~:text=Size%20Specifies%20the%20size%20of,e%2C%20Size%20must%20be%201">[15]</a>
ba (Break on Access) - Windows drivers | Microsoft Learn</p>

<p><a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-">https://learn.microsoft.com/en-us/windows-hardware/drivers/debuggercmds/ba--break-on-access-</a></p>

<p><a href="https://devblogs.microsoft.com/cppblog/whats-new-for-c-debugging-in-visual-studio-code/#:~:text=To%20set%20a%20data%20breakpoint,select%20Break%20on%20Value%20Change">[12]</a>
What’s new for C++ Debugging in Visual Studio Code - C++ Team Blog</p>

<p><a href="https://devblogs.microsoft.com/cppblog/whats-new-for-c-debugging-in-visual-studio-code/">https://devblogs.microsoft.com/cppblog/whats-new-for-c-debugging-in-visual-studio-code/</a></p>

<p><a href="https://stackoverflow.com/questions/18721841/how-to-find-the-source-of-a-stackoverflowexception-in-my-application#:~:text=that%20raised%20the%20exception%2C%20and,will%20be%20something%20like%20this">[18]</a>
c# - How to find the source of a StackOverflowException in my
application - Stack Overflow</p>

<p><a href="https://stackoverflow.com/questions/18721841/how-to-find-the-source-of-a-stackoverflowexception-in-my-application">https://stackoverflow.com/questions/18721841/how-to-find-the-source-of-a-stackoverflowexception-in-my-application</a></p>]]></content><author><name>Colin Neilens</name></author><category term="cpp" /><category term="debugging" /><category term="case-studies" /><summary type="html"><![CDATA[In this third part of our series, we’ll walk through multiple debugging case studies involving memory corruption, crashes, and undefined behavior in C++ programs. We’ll use the same buggy code in each case and debug it step-by-step with four different tools/environments:]]></summary></entry><entry><title type="html">Debugging Memory Corruption Like a Senior Engineer</title><link href="https://kobolinsapps.com/2026/01/15/debugging-memory-corruption/" rel="alternate" type="text/html" title="Debugging Memory Corruption Like a Senior Engineer" /><published>2026-01-15T10:00:00+00:00</published><updated>2026-01-15T10:00:00+00:00</updated><id>https://kobolinsapps.com/2026/01/15/debugging-memory-corruption</id><content type="html" xml:base="https://kobolinsapps.com/2026/01/15/debugging-memory-corruption/"><![CDATA[<p>Memory corruption bugs – such as double frees, use-after-frees,
out-of-bounds writes, stack overflows, or using unallocated memory –
are among the most insidious issues in C and C++
development<a href="https://mohitmishra786.github.io/TheCoreDump/posts/Advanced-Memory-Debugging-in-C-A-Deep-Dive-into-Valgrind-and-AddressSanitizer/#:~:text=Memory,potentially%20lying%20dormant%20until%20specific">[1]</a>.
They can lurk unnoticed, causing subtle data corruption or <strong>“undefined
behavior”</strong> that only triggers crashes under specific
conditions<a href="https://mohitmishra786.github.io/TheCoreDump/posts/Advanced-Memory-Debugging-in-C-A-Deep-Dive-into-Valgrind-and-AddressSanitizer/#:~:text=Memory,potentially%20lying%20dormant%20until%20specific">[1]</a>.
In this post, we’ll explore how a senior engineer methodically tracks
down these bugs. We’ll cover both <strong>modern tools (like
AddressSanitizer)</strong> and <strong>old-school techniques (when such tools aren’t
available)</strong>. Finally, we’ll discuss <strong>C++ undefined behavior</strong> issues
and how to debug them with and without UndefinedBehaviorSanitizer
(UBSan).</p>

<h2 id="common-memory-corruption-culprits">Common Memory Corruption Culprits</h2>

<p>Before diving into debugging strategies, let’s recap the usual suspects
in memory corruption:</p>

<ul>
  <li><strong>Double Free:</strong> Freeing the same pointer twice. This often leads to
heap metadata corruption or an immediate runtime error (many C
libraries detect this and abort).</li>
  <li><strong>Use-After-Free:</strong> Accessing memory after it’s been freed (dangling
pointer access). This can cause sporadic crashes or corrupted data,
since the memory may be reallocated for other uses.</li>
  <li><strong>Heap Buffer Overflow (Out-of-Bounds):</strong> Writing outside the bounds
of a heap allocation (buffer overflow) or reading out-of-bounds. This
can overwrite adjacent memory or control data, leading to
unpredictable behavior or security vulnerabilities.</li>
  <li><strong>Stack Buffer Overflow:</strong> Writing past the end of a stack-allocated
array (or deep recursion causing stack exhaustion). This can overwrite
the function’s return address or nearby variables. Modern compilers
often employ <em>stack canaries</em> – special guard values – to detect
such overflow. If a canary value is found altered at function return,
the program terminates as a protective
measure<a href="https://www.sans.org/blog/stack-canaries-gingerly-sidestepping-the-cage#:~:text=buffer%20overflow%20attacks,But%20not%20impossible">[2]</a>.</li>
  <li><strong>Using Unallocated/Uninitialized Memory:</strong> Dereferencing pointers
that were never allocated or that have gone out of scope, as well as
using variables that were never initialized. This can read or write
random memory, with results ranging from no visible effect to
immediate crashes.</li>
  <li><strong>Invalid Free:</strong> Freeing memory that <strong>was never allocated</strong> or has
already been freed (related to double free). C runtime will usually
catch some of these and abort.</li>
</ul>

<p>Each of these issues leads to <strong>undefined behavior</strong> in C/C++ – meaning
the program’s behavior is not predictable by the language standard. Now,
let’s see how to catch and diagnose them effectively.</p>

<h2 id="using-addresssanitizer-asan-and-modern-tools">Using AddressSanitizer (ASan) and Modern Tools</h2>

<p>One of the first tools in a seasoned engineer’s toolbox is
<strong>AddressSanitizer (ASan)</strong>. ASan is a fast memory error detector built
into modern compilers (GCC, Clang, and even
MSVC)<a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=Getting%20started%20with%20ASan">[3]</a>.
When you compile a program with <code class="language-plaintext highlighter-rouge">-fsanitize=address</code>, the compiler
instruments the binary to detect illegal memory accesses at
runtime<a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=Getting%20started%20with%20ASan">[3]</a>.
The program runs slightly slower (~2x overhead) but catches a wide
range of errors <strong>at the moment they
occur</strong><a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=AddressSanitizer%E2%80%99s%20approach%20differs%20from%20other,and%20may%20detect%20fewer%20bugs">[4]</a>.</p>

<p><strong>What ASan Catches:</strong> ASan can detect <strong>heap buffer overflows, stack
buffer overflows, use-after-free, double free, use-after-scope (stack
use after return), and
more<a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=It%20is%20also%20worth%20noting,memory%20was%20allocated%20and%20freed">[5]</a></strong>.
For example, writing one byte past a malloc’ed buffer or accessing an
object after it’s freed will immediately trigger ASan’s error report.</p>

<p><strong>How ASan Works:</strong> Under the hood, ASan uses “red zones” and shadow
memory. It pads heap allocations with guard regions and marks freed
memory as poisoned. Any access into those regions is trapped. For stack
variables, it places guard canaries around them similar to security
cookies. This approach lets ASan stop the program exactly where the
invalid access happens, rather than long after the damage is done.</p>

<p><strong>Interpreting ASan Reports:</strong> When ASan finds an error, it prints a
detailed report. This includes the error type (e.g.
“heap-buffer-overflow” or “use-after-free”), a stack trace showing where
the invalid memory access happened, and often where the memory was
originally allocated and freed. For example, an ASan error might say:</p>

<blockquote>
  <p><code class="language-plaintext highlighter-rouge">ERROR: AddressSanitizer: heap-use-after-free on address 0x602000000014</code>
… and show the allocation stack trace and the free stack trace.</p>
</blockquote>

<p>ASan’s output is extremely helpful for pinpointing the root cause. It
might indicate that a block allocated at function X and freed at
function Y was later accessed in function Z – which is exactly the
chain you need to fix.</p>

<p><strong>Example:</strong> Suppose we have a heap out-of-bounds bug. ASan would catch
it like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>==1==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000014
READ of size 1 at 0x502000000014 thread T0
    #0 0x5591ad37f522 in out_of_bounds(char const*) example.cpp:5:45
    #1 0x5591ad37f59a in main example.cpp:10:4
    … 
0x502000000014 is located 0 bytes after 4-byte region [0x502000000010,0x502000000014) allocated by thread T0 here:
    #0 0x555e42ab02bd in operator new[](unsigned long) (asan_new_delete.cpp:98)
    #1 0x555e42ab2571 in main example.cpp:9:16
</code></pre></div></div>

<p>This tells us a 4-byte array was allocated (at <code class="language-plaintext highlighter-rouge">main</code> line 9), and an
overflow happened when reading index 4 (at <code class="language-plaintext highlighter-rouge">out_of_bounds</code> line 5) – an
off-by-one error. ASan even notes the accessed address is right after
the allocated
region<a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=Program%20stderr%20%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20%3D%3D1%3D%3DERROR%3A%20AddressSanitizer%3A,gnu%2Flibc.so.6%2B0x29d8f%29%20%28BuildId">[6]</a><a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=0x502000000014%20is%20located%200%20bytes,gnu%2Flibc.so.6%2B0x29d8f%29%20%28BuildId%3A%20c289da5071a3399de893d2af81d6a30c62646e1e">[7]</a>.</p>

<p><strong>Comparing to Valgrind:</strong> Another popular tool is Valgrind’s Memcheck,
which can detect similar issues <strong>without needing to recompile</strong> (you
run your program under Valgrind). However, Valgrind typically runs the
program much slower (20x slowdown vs ~2x for ASan) and can miss some
bugs<a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=AddressSanitizer%E2%80%99s%20approach%20differs%20from%20other,and%20may%20detect%20fewer%20bugs">[4]</a>.
Still, if you only have a production binary and need to investigate a
memory bug, running it under Valgrind is a solid option. It will flag
invalid reads/writes, use-after-free, double frees, etc., along with
stack traces.</p>

<p><strong>Other Tools:</strong> There are other specialized tools and libraries as
well:</p>

<ul>
  <li><strong>Electric Fence</strong> and <strong>Page Heap</strong>: These place each allocation on
its own memory page with an unmapped guard page after it. Any buffer
overflow causes an immediate segmentation fault at the guard page.
This is heavy on memory but effective for debugging.</li>
  <li><strong>glibc Malloc Debugging:</strong> The GNU C library provides some built-in
checking if enabled. For example, setting environment variable
<code class="language-plaintext highlighter-rouge">MALLOC_CHECK_=3</code> activates a special heap implementation that is
<em>“tolerant against simple errors, such as double free of the same
pointer or one-byte
overflows”</em><a href="https://stackoverflow.com/questions/18153746/what-is-the-difference-between-glibcs-malloc-check-m-check-action-and-mcheck#:~:text=,When">[8]</a>.
In practice, glibc will detect these cases and abort the program with
an error message (e.g. "<strong>glibc detected</strong> <em>double free or
corruption</em>*"). Likewise, <code class="language-plaintext highlighter-rouge">MALLOC_PERTURB_</code> can be set (e.g. to a
non-zero byte value) to fill freed memory with a pattern, making
use-after-free more likely to crash and be noticed.</li>
  <li><strong>Custom Debug Allocators:</strong> A senior engineer might use a custom
debugging allocator in development. These allocators often <strong>don’t
re-use freed memory immediately</strong> and <strong>pad allocations with guard
bytes</strong>, so that temporal and spatial bugs are
exposed<a href="http://scottmcpeak.com/memory-errors/#:~:text=%2A%20Don%27t%20re,empty%20space%20between%20memory%20blocks">[9]</a>.
For example, one strategy is to fill freed memory with a known bad
value (like 0xDEADBEEF or 0xDD in hex) and check those patterns on
each allocation/free. If a pattern is disturbed, you know a buffer
overflow
occurred<a href="http://scottmcpeak.com/memory-errors/#:~:text=Second%2C%20by%20putting%20empty%20space,known%20value%20has%20been%20changed">[10]</a>.
Similarly, not reusing memory quickly ensures use-after-free crashes
rather than silently reusing the freed block for something
else<a href="http://scottmcpeak.com/memory-errors/#:~:text=Why%20do%20these%20techniques%20help%3F,blocks%20are%20allocated%20and%20deallocated">[11]</a>.</li>
</ul>

<p>In summary, <strong>during development, enabling tools like ASan is often the
quickest way to catch memory corruption</strong>. A senior engineer will
usually run test suites under ASan/Valgrind regularly, making it far
easier to locate the source of these bugs before they hit production.</p>

<h2 id="debugging-memory-bugs-without-asan">Debugging Memory Bugs <em>Without</em> ASan</h2>

<p>Sometimes you encounter memory corruption in an environment where
sanitizers aren’t available (or a bug appears in a production build
compiled without them). In these cases, a seasoned engineer falls back
on fundamental debugging techniques:</p>

<ul>
  <li>
    <p><strong>Recognize the Symptoms:</strong> Memory corruption can manifest as random
crashes, strange values in variables, or deterministic aborts with
messages (like “double free or corruption” or “stack smashing
detected”). The <em>symptom</em> often occurs far from the <em>cause</em>. For
example, an out-of-bounds write might corrupt an unrelated data
structure, causing a crash much later. So, treat any odd crash or
inconsistent state as a potential memory bug until proven otherwise.</p>
  </li>
  <li>
    <p><strong>Use Debug Builds &amp; Flags:</strong> Re-run the program with debugging
features on. Enable compiler stack protection
(<code class="language-plaintext highlighter-rouge">-fstack-protector-strong</code> in GCC/Clang, or <code class="language-plaintext highlighter-rouge">/GS</code> in MSVC) to catch
stack buffer overflows (the infamous "<em>stack canary</em>" that triggers
an abort on
detection<a href="https://www.sans.org/blog/stack-canaries-gingerly-sidestepping-the-cage#:~:text=buffer%20overflow%20attacks,But%20not%20impossible">[2]</a>).
Use library debug modes if available (for example, many C++ standard
libraries have an <code class="language-plaintext highlighter-rouge">_GLIBCXX_DEBUG</code> mode that turns on iterator bounds
checking and diagnostics, catching some UB in containers).</p>
  </li>
  <li>
    <p><strong>Binary Search with Logging:</strong> If you don’t know where the corruption
is happening, instrument the code with logging or assertions at
strategic points. By narrowing down where things go wrong, you can
find the approximate section of code responsible. For instance, you
might sprinkle checksums or sanity-check functions to verify data
structure integrity at intervals to pinpoint when corruption first
appears.</p>
  </li>
  <li>
    <p><strong>Reproduce and Isolate:</strong> Try to get a reproducible case. If the bug
is timing-dependent or input-dependent, write a smaller test or run
with a fixed seed. Once reproducible, you can bisect the code or input
to narrow it down. Version control <code class="language-plaintext highlighter-rouge">git bisect</code> is invaluable if you
suspect the bug was introduced by a certain commit – you can test
older revisions to find when it first appeared.</p>
  </li>
  <li>
    <p><strong>Debugger Watchpoints:</strong> A powerful but underused technique is
setting hardware watchpoints on memory addresses. Once you identify a
specific memory location that gets corrupted (say you found an object
that mysteriously changes value), you can ask the debugger to break
<strong>when that memory is written</strong>. In GDB, for example,
<code class="language-plaintext highlighter-rouge">watch *((int*)0xABCDEF)</code> will pause execution at the exact moment
address <code class="language-plaintext highlighter-rouge">0xABCDEF</code> is
modified<a href="http://scottmcpeak.com/memory-errors/#:~:text=In%20gdb%2C%20the%20notation%20for,at%20the%20gdb%20prompt%20type">[12]</a><a href="http://scottmcpeak.com/memory-errors/#:~:text=%28gdb%29%20watch%20">[13]</a>.
The challenge is you need a stable address to watch (the memory must
be allocated at a known location or you need to catch it after
allocation but before corruption). In practice, one might run until a
corruption is noticed, note the bad address, then restart the program,
set a watchpoint on that address after allocation, and continue until
it triggers. This can directly pinpoint the line of code responsible
for a stray
write<a href="http://scottmcpeak.com/memory-errors/#:~:text=Intel,which%20byte%20is%20being%20overwritten">[14]</a><a href="http://scottmcpeak.com/memory-errors/#:~:text=%28gdb%29%20watch%20">[13]</a>.</p>
  </li>
  <li>
    <p><strong>Core Dumps and Post-mortem Analysis:</strong> If a bug only happens in
production (where you can’t run interactive debuggers), enabling core
dumps is vital. A core dump captures the process memory and state at
crash time. A senior engineer will load the core into GDB or lldb and
inspect the stack trace and memory. For example, a double free crash
might show a stack trace deep inside the <code class="language-plaintext highlighter-rouge">free()</code> function, indicating
the second free call. Looking at the arguments passed to <code class="language-plaintext highlighter-rouge">free</code> and
cross-referencing with logs or memory maps can reveal which pointer
was freed twice and where it was originally allocated. Tools like
<code class="language-plaintext highlighter-rouge">addr2line</code> can translate addresses to line numbers if debug symbols
are available.</p>
  </li>
  <li>
    <p><strong>Heap Consistency Checkers:</strong> Some libc implementations and OSes have
heap checking modes. We mentioned <code class="language-plaintext highlighter-rouge">MALLOC_CHECK_</code> for glibc which will
<em>abort on heap inconsistencies</em> like double frees or tiny
overflows<a href="https://stackoverflow.com/questions/18153746/what-is-the-difference-between-glibcs-malloc-check-m-check-action-and-mcheck#:~:text=,When">[8]</a>.
On Windows, one can enable <em>Page Heap</em> (via gflags or the Application
Verifier) for a process, which places allocations on dedicated pages
with guard regions – causing any out-of-bounds access to instantly
fault, and also catching use-after-free by making freed pages
inaccessible. These can often be enabled outside of the program (as
settings or environment variables) without code changes.</p>
  </li>
  <li>
    <p><strong>Valgrind or Similar Emulators:</strong> If you can’t compile with ASan,
running under Valgrind is still an option even for a release binary.
It will systematically check each memory access. A trick: if the bug
is timing-sensitive (e.g. a race), Valgrind’s slowdown might mask it.
But for purely memory bugs, it usually still finds them. Valgrind’s
output will tell you the type of error and stack trace at the point of
bad access, similar to ASan (though sometimes with less detail on
allocation origin).</p>
  </li>
  <li>
    <p><strong>Statistical and Fuzzy Methods:</strong> If all else fails, you can resort
to brute force testing. For instance, if the issue might be
input-dependent, use fuzz testing on the module while running under a
memory checker to try to trigger the corruption. This is how many
security bugs are found. A senior engineer might also write a quick
script to run the program 1000 times under different conditions to see
if the crash can be caught and studied.</p>
  </li>
</ul>

<p>In a nutshell, <strong>without sanitizers you rely on careful detective work</strong>
– using debuggers, logs, and the occasional trick to catch the culprit
in the act. It often involves “drawing a circle” around the bug by
gathering clues and progressively zeroing in on the cause.</p>

<h2 id="c-undefined-behavior-finding-the-invisible-bugs">C++ Undefined Behavior: Finding the Invisible Bugs</h2>

<p>Undefined Behavior (UB) in C++ is any program operation that the C++
standard does not define what should happen. Memory corruption is one
big source of UB, but there are many others: using an uninitialized
variable, overflowing a signed integer, dereferencing a null or
misaligned pointer, violating type aliasing rules, data races, etc. With
UB, <strong>the program might appear to work normally, or it might misbehave
in bizarre ways</strong> – anything can happen. Debugging UB can be tricky
because the symptoms are not always directly tied to the root cause.</p>

<p><strong>Examples of UB:</strong></p>

<ul>
  <li>Signed integer overflow (e.g., adding 1 to INT_MAX) is UB – the
program might wrap around or not, compilers are free to assume it
never
happens<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,bounds%20can%20be%20statically%20determined">[15]</a>.</li>
  <li>Dereferencing a null or wildly misaligned pointer is
UB<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,bounds%20for%20their%20data%20type">[16]</a>
(usually crashes, but not guaranteed in all systems).</li>
  <li>Accessing an array out-of-bounds is UB (even if it’s just reading one
past the end – sometimes it might read some memory, other times you
get lucky and hit an unmapped page causing a crash).</li>
  <li>Using a pointer or reference to an object that has gone out of scope
or been deleted (dangling reference).</li>
  <li>Violating object lifetimes (calling methods on a moved-from C++ object
that doesn’t allow it, or using an invalidated iterator in a
container).</li>
  <li>Data races (two threads accessing the same variable without
synchronization, where at least one is a write) – this is UB that
often shows up as random crashes or wrong values.</li>
</ul>

<p>Undefined behavior issues often surface as <strong>“Heisenbugs”</strong> – e.g., the
program works in Debug mode but fails with optimizations on, or adding a
<code class="language-plaintext highlighter-rouge">printf</code> makes the bug disappear. This is because compilers may optimize
based on the assumption “UB never happens,” so when it <em>does</em> happen,
the optimized code might behave very strangely.</p>

<h3 id="using-ubsan-to-catch-undefined-behavior">Using UBSan to Catch Undefined Behavior</h3>

<p>To systematically catch many kinds of UB, compilers offer
<strong>UndefinedBehaviorSanitizer (UBSan)</strong>. This is enabled with
<code class="language-plaintext highlighter-rouge">-fsanitize=undefined</code> (on Clang and GCC) during
compilation<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=Use%20,if%20you%E2%80%99re%20compiling%2Flinking%20C%20code">[17]</a>.
UBSan instruments the code to check for various undefined conditions at
runtime<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=UndefinedBehaviorSanitizer%20,during%20program%20execution%2C%20for%20example">[18]</a>.
It covers things like:</p>

<ul>
  <li><strong>Array index out-of-bounds</strong> (for cases where the compiler can
determine the index is out of
range)<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=UndefinedBehaviorSanitizer%20,during%20program%20execution%2C%20for%20example">[18]</a>.</li>
  <li><strong>Null or Misaligned Pointer
Dereferences</strong><a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,bounds%20for%20their%20data%20type">[16]</a>.</li>
  <li><strong>Invalid</strong> <code class="language-plaintext highlighter-rouge">bool</code> <strong>values</strong> (reading a bool that isn’t 0 or 1).</li>
  <li><strong>Enumeration value out of range</strong> (reading an enum with an invalid
value).</li>
  <li><strong>Integer overflow</strong> (signed overflow, divide-by-zero,
etc.)<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,bounds%20for%20their%20data%20type">[19]</a>.</li>
  <li><strong>Incorrect use of</strong> <code class="language-plaintext highlighter-rouge">reinterpret_cast</code> (e.g., violating type aliasing
rules resulting in UB).</li>
  <li><strong>Undefined shift amounts</strong> (shifting bits by a negative or too-large
amount).</li>
  <li><strong>Use of uninitialized memory</strong> (for stack variables) – though this
is better covered by MemorySanitizer, UBSan has some checks for using
uninitialized bools etc.</li>
</ul>

<p>When UBSan detects an issue, it prints a warning (typically to stderr)
describing the problem and the source location. For example, with UBSan
a signed overflow might produce:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
</code></pre></div></div>

<p><a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=%25%20clang%2B%2B%20,be%20represented%20in%20type%20%27int">[20]</a>.
Unlike ASan, UBSan by default doesn’t halt the program on the first
issue (it prints a warning and lets execution continue) – but you can
configure it to abort if desired. The key benefit is it points out code
that invokes UB <em>even if it doesn’t crash</em>. This lets you proactively
fix bugs that could blow up later.</p>

<p>A senior engineer will often run test suites under UBSan (and other
sanitizers concurrently, since they can be combined) to flush out hidden
issues. For instance, UBSan might catch that a loop’s index goes beyond
an array’s length (even if it luckily only reads benign memory). Or it
might catch that your code does <code class="language-plaintext highlighter-rouge">1 &lt;&lt; 31</code> on a 32-bit int, which is UB
if that int is signed.</p>

<p><strong>Note:</strong> UBSan does <strong>not</strong> catch all forms of UB. Notably, it won’t
automatically catch use-after-free or buffer overflow (those are ASan’s
domain), and it doesn’t catch data races (ThreadSanitizer does that). It
focuses on the more “semantic” undefined behaviors in code logic.</p>

<h3 id="debugging-undefined-behavior-without-ubsan">Debugging Undefined Behavior Without UBSan</h3>

<p>If you suspect an undefined-behavior issue but cannot use UBSan,
debugging becomes more investigative. Here are approaches a veteran
engineer might use:</p>

<ul>
  <li>
    <p><strong>Compiler Warnings and Static Analysis:</strong> First, compile with a high
warning level (<code class="language-plaintext highlighter-rouge">-Wall -Wextra -pedantic</code> in GCC/Clang). Many times, UB
stems from questionable code that compilers can warn about (like
“comparison is always false due to limited range,” which could hint at
an overflow or logic issue). Static analysis tools or linters (like
clang-tidy, Coverity, etc.) can also flag suspicious constructs (e.g.,
use of uninitialized variables, potential null dereferences).</p>
  </li>
  <li>
    <p><strong>Run on Multiple Platforms/Compilers:</strong> If the code’s behavior
changes between Debug vs Release or between different compilers,
that’s a red flag for UB. For example, if optimization level <code class="language-plaintext highlighter-rouge">-O2</code>
causes a bug to appear, try <code class="language-plaintext highlighter-rouge">-O0</code> (no optimization) – stable under
<code class="language-plaintext highlighter-rouge">-O0</code> but not under <code class="language-plaintext highlighter-rouge">-O2</code> often means something like an uninitialized
variable (which might accidentally work when memory is zeroed in
debug) or an undefined order of evaluation that the optimizer
rearranged. Testing on another compiler or OS can also give clues –
some UB might crash on one system but not another.</p>
  </li>
  <li>
    <p><strong>Assertions and Defensive Checks:</strong> Add runtime checks in the code to
catch bad states. For instance, if you suspect an index might go out
of range, add an <code class="language-plaintext highlighter-rouge">assert(index &lt; size)</code>. If you think an integer might
overflow, check before arithmetic (e.g., if (a &gt; MAX_INT - b) handle
error). In debug builds these assertions will fire and give you a line
number if violated. While this doesn’t <em>solve</em> UB, it can detect it
closer to the source.</p>
  </li>
  <li>
    <p><strong>Simplify and Inspect:</strong> Try to reduce the problem. Comment out or
disable parts of the code to see if the issue disappears. If removing
a certain function call avoids the weird behavior, inspect that
function for UB (maybe it modifies something it shouldn’t, or relies
on undefined order of evaluation). Gradually narrow it down to a
minimal sequence that still reproduces the odd behavior, then
scrutinize that code for anything non-portable or undefined by the
standard.</p>
  </li>
  <li>
    <p><strong>Use Library Debug Modes:</strong> Many C++ libraries have debug
instrumentation. For example, the C++ standard library in debug mode
(enabled by <code class="language-plaintext highlighter-rouge">_GLIBCXX_DEBUG</code> in GCC’s libstdc++, or using the MSVC
debug runtime) will perform extra checks – like verifying that you
don’t dereference end iterators, that container sizes are correct,
etc. If the bug disappears in debug mode but is present in release,
the debug mode might also <strong>report an error</strong> (like “vector iterator
not dereferencable”) which pinpoints the UB (like using an invalidated
iterator).</p>
  </li>
  <li>
    <p><strong>Check for Common UB Patterns:</strong> Some classic culprits to manually
review in code:</p>
  </li>
  <li>
    <p><em>Iterator invalidation:</em> Are we erasing elements of a container in a
loop with an iterator? Using an iterator after modifying the
container?</p>
  </li>
  <li>
    <p><em>Object lifetime:</em> Returning references to local variables (dangling
reference), or calling a method on an object after it’s been moved or
freed.</p>
  </li>
  <li>
    <p><em>Alignment assumptions:</em> Casting between types that may have stricter
alignment (for instance, casting a <code class="language-plaintext highlighter-rouge">char*</code> from malloc to a type
requiring 8-byte alignment without ensuring the allocation aligned –
usually not an issue with <code class="language-plaintext highlighter-rouge">malloc</code> but can be with manual memory
pools).</p>
  </li>
  <li>
    <p><em>Strict aliasing:</em> Accessing an object through a pointer of an
incompatible type (breaking aliasing rules). This can fool the
optimizer. Example: writing to a float and reading as an int through a
pointer is UB (unless using <code class="language-plaintext highlighter-rouge">memcpy</code> or union). If suspect, compile
with <code class="language-plaintext highlighter-rouge">-fno-strict-aliasing</code> as a test.</p>
  </li>
  <li>
    <p><em>Missing</em> <code class="language-plaintext highlighter-rouge">return</code> <em>statement:</em> In C++, falling off the end of a
non-void function without returning a value is UB. Surprisingly common
and can cause bizarre issues.</p>
  </li>
  <li>
    <p><em>Uninitialized reads:</em> Make sure every code path initializes
variables. Even if you don’t have MemorySanitizer, you can sometimes
catch this by adding prints or using tools like Valgrind (Valgrind
will flag uses of uninitialized memory). Or set all memory to a known
value (e.g., <code class="language-plaintext highlighter-rouge">memset(struct, 0xAA, sizeof struct)</code> after allocating a
struct) to see if that triggers something obvious.</p>
  </li>
  <li>
    <p><strong>Leverage Thread Sanitizer for Concurrency:</strong> If you suspect a
multi-threading issue (which is UB if data races occur), running under
ThreadSanitizer (<code class="language-plaintext highlighter-rouge">-fsanitize=thread</code>) can pinpoint data races and
synchronization issues. A data race might manifest as random crashes
or wrong values without any other apparent cause.</p>
  </li>
</ul>

<p>Finally, when an undefined behavior bug is found and fixed, it’s wise to
add a regression test. Senior engineers often augment their test suites
with cases that would catch that specific issue if it ever reappears
(for example, if the bug was an overflow with certain inputs, add a test
for that input with UBSan enabled).</p>

<h2 id="conclusion">Conclusion</h2>

<p>Debugging memory corruption and undefined behavior is a challenging
task, but with the right approach it becomes manageable. A senior
engineer combines <strong>modern tools</strong> (ASan, UBSan, Valgrind, etc.) with
<strong>core debugging skills</strong> (breakpoints, watchpoints, careful code
review) to track down these bugs. The key steps are to <strong>make bugs
visible</strong> (using sanitizers or forcing errors to
surface)<a href="http://scottmcpeak.com/memory-errors/#:~:text=Second%2C%20by%20putting%20empty%20space,known%20value%20has%20been%20changed">[10]</a>,
gather clues from crashes or logs, and iteratively narrow the search
space. Always remember that memory bugs often <strong>appear far from their
origin</strong>, so a methodical approach is crucial. By using the techniques
above – from AddressSanitizer’s instant error reports to careful manual
instrumentation – you can find and fix even the nastiest memory
corruption issues and ensure your C++ code behaves correctly (and
<em>definedly</em> 😉).</p>

<p><strong>Sources:</strong></p>

<ul>
  <li>Mohit Mishra, <em>Advanced Memory Debugging in C: Valgrind and
AddressSanitizer</em> – on common memory bug types and
tools<a href="https://mohitmishra786.github.io/TheCoreDump/posts/Advanced-Memory-Debugging-in-C-A-Deep-Dive-into-Valgrind-and-AddressSanitizer/#:~:text=Memory,potentially%20lying%20dormant%20until%20specific">[1]</a>.</li>
  <li>Trail of Bits, <em>Understanding AddressSanitizer</em> – on enabling ASan
and error types it
detects<a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=Getting%20started%20with%20ASan">[3]</a><a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=It%20is%20also%20worth%20noting,memory%20was%20allocated%20and%20freed">[5]</a>.</li>
  <li>GNU C Library Manual – notes on <code class="language-plaintext highlighter-rouge">MALLOC_CHECK_</code> catching double frees
and off-by-one
errors<a href="https://stackoverflow.com/questions/18153746/what-is-the-difference-between-glibcs-malloc-check-m-check-action-and-mcheck#:~:text=,When">[8]</a>.</li>
  <li>Scott McPeak, <em>Debugging Memory Errors in C/C++</em> – techniques like
not reusing memory and guard zones in debug
allocators<a href="http://scottmcpeak.com/memory-errors/#:~:text=%2A%20Don%27t%20re,empty%20space%20between%20memory%20blocks">[9]</a>,
and using hardware watchpoints in
GDB<a href="http://scottmcpeak.com/memory-errors/#:~:text=In%20gdb%2C%20the%20notation%20for,at%20the%20gdb%20prompt%20type">[12]</a><a href="http://scottmcpeak.com/memory-errors/#:~:text=%28gdb%29%20watch%20">[13]</a>.</li>
  <li>SANS Institute, <em>Stack Canaries</em> – explanation of stack canary values
aborting the program on overflow
detection<a href="https://www.sans.org/blog/stack-canaries-gingerly-sidestepping-the-cage#:~:text=buffer%20overflow%20attacks,But%20not%20impossible">[2]</a>.</li>
  <li>Clang Documentation, <em>UndefinedBehaviorSanitizer</em> – lists of UB that
UBSan can catch (out-of-bounds, misaligned pointers,
etc.)<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=UndefinedBehaviorSanitizer%20,during%20program%20execution%2C%20for%20example">[18]</a>
and example UBSan runtime error
messages<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=%25%20clang%2B%2B%20,be%20represented%20in%20type%20%27int">[20]</a>.</li>
</ul>

<hr />

<p><a href="https://mohitmishra786.github.io/TheCoreDump/posts/Advanced-Memory-Debugging-in-C-A-Deep-Dive-into-Valgrind-and-AddressSanitizer/#:~:text=Memory,potentially%20lying%20dormant%20until%20specific">[1]</a>
Advanced Memory Debugging in C: A Deep Dive into Valgrind and
AddressSanitizer | TheCoreDump</p>

<p><a href="https://mohitmishra786.github.io/TheCoreDump/posts/Advanced-Memory-Debugging-in-C-A-Deep-Dive-into-Valgrind-and-AddressSanitizer/">https://mohitmishra786.github.io/TheCoreDump/posts/Advanced-Memory-Debugging-in-C-A-Deep-Dive-into-Valgrind-and-AddressSanitizer/</a></p>

<p><a href="https://www.sans.org/blog/stack-canaries-gingerly-sidestepping-the-cage#:~:text=buffer%20overflow%20attacks,But%20not%20impossible">[2]</a>
Stack Canaries – Gingerly Sidestepping the Cage | SANS Institute</p>

<p><a href="https://www.sans.org/blog/stack-canaries-gingerly-sidestepping-the-cage">https://www.sans.org/blog/stack-canaries-gingerly-sidestepping-the-cage</a></p>

<p><a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=Getting%20started%20with%20ASan">[3]</a>
<a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=AddressSanitizer%E2%80%99s%20approach%20differs%20from%20other,and%20may%20detect%20fewer%20bugs">[4]</a>
<a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=It%20is%20also%20worth%20noting,memory%20was%20allocated%20and%20freed">[5]</a>
<a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=Program%20stderr%20%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%20%3D%3D1%3D%3DERROR%3A%20AddressSanitizer%3A,gnu%2Flibc.so.6%2B0x29d8f%29%20%28BuildId">[6]</a>
<a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/#:~:text=0x502000000014%20is%20located%200%20bytes,gnu%2Flibc.so.6%2B0x29d8f%29%20%28BuildId%3A%20c289da5071a3399de893d2af81d6a30c62646e1e">[7]</a>
Understanding AddressSanitizer: Better memory safety for your code - The
Trail of Bits Blog</p>

<p><a href="https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/">https://blog.trailofbits.com/2024/05/16/understanding-addresssanitizer-better-memory-safety-for-your-code/</a></p>

<p><a href="https://stackoverflow.com/questions/18153746/what-is-the-difference-between-glibcs-malloc-check-m-check-action-and-mcheck#:~:text=,When">[8]</a>
debugging - What is the difference between glibc's MALLOC_CHECK_,
M_CHECK_ACTION, and mcheck? - Stack Overflow</p>

<p><a href="https://stackoverflow.com/questions/18153746/what-is-the-difference-between-glibcs-malloc-check-m-check-action-and-mcheck">https://stackoverflow.com/questions/18153746/what-is-the-difference-between-glibcs-malloc-check-m-check-action-and-mcheck</a></p>

<p><a href="http://scottmcpeak.com/memory-errors/#:~:text=%2A%20Don%27t%20re,empty%20space%20between%20memory%20blocks">[9]</a>
<a href="http://scottmcpeak.com/memory-errors/#:~:text=Second%2C%20by%20putting%20empty%20space,known%20value%20has%20been%20changed">[10]</a>
<a href="http://scottmcpeak.com/memory-errors/#:~:text=Why%20do%20these%20techniques%20help%3F,blocks%20are%20allocated%20and%20deallocated">[11]</a>
<a href="http://scottmcpeak.com/memory-errors/#:~:text=In%20gdb%2C%20the%20notation%20for,at%20the%20gdb%20prompt%20type">[12]</a>
<a href="http://scottmcpeak.com/memory-errors/#:~:text=%28gdb%29%20watch%20">[13]</a>
<a href="http://scottmcpeak.com/memory-errors/#:~:text=Intel,which%20byte%20is%20being%20overwritten">[14]</a>
Debugging Memory Errors in C/C++</p>

<p><a href="http://scottmcpeak.com/memory-errors/">http://scottmcpeak.com/memory-errors/</a></p>

<p><a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,bounds%20can%20be%20statically%20determined">[15]</a>
<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,bounds%20for%20their%20data%20type">[16]</a>
<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=Use%20,if%20you%E2%80%99re%20compiling%2Flinking%20C%20code">[17]</a>
<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=UndefinedBehaviorSanitizer%20,during%20program%20execution%2C%20for%20example">[18]</a>
<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=,bounds%20for%20their%20data%20type">[19]</a>
<a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#:~:text=%25%20clang%2B%2B%20,be%20represented%20in%20type%20%27int">[20]</a>
UndefinedBehaviorSanitizer — Clang 23.0.0git documentation</p>

<p><a href="https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html">https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html</a></p>]]></content><author><name>Colin Neilens</name></author><category term="cpp" /><category term="debugging" /><category term="memory" /><summary type="html"><![CDATA[Memory corruption bugs – such as double frees, use-after-frees, out-of-bounds writes, stack overflows, or using unallocated memory – are among the most insidious issues in C and C++ development[1]. They can lurk unnoticed, causing subtle data corruption or “undefined behavior” that only triggers crashes under specific conditions[1]. In this post, we’ll explore how a senior engineer methodically tracks down these bugs. We’ll cover both modern tools (like AddressSanitizer) and old-school techniques (when such tools aren’t available). Finally, we’ll discuss C++ undefined behavior issues and how to debug them with and without UndefinedBehaviorSanitizer (UBSan).]]></summary></entry><entry><title type="html">Debugging C++ Applications: A Senior Engineer’s Guide</title><link href="https://kobolinsapps.com/2026/01/14/debugging-cpp-applications/" rel="alternate" type="text/html" title="Debugging C++ Applications: A Senior Engineer’s Guide" /><published>2026-01-14T10:00:00+00:00</published><updated>2026-01-14T10:00:00+00:00</updated><id>https://kobolinsapps.com/2026/01/14/debugging-cpp-applications</id><content type="html" xml:base="https://kobolinsapps.com/2026/01/14/debugging-cpp-applications/"><![CDATA[<p>Debugging is an essential skill for every software engineer. As Brian
Kernighan famously noted, <em>“Debugging is twice as hard as writing a
program in the first place. So if you’re as clever as you can be when
you write it, how will you ever debug
it?”</em><a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,%E2%80%95%20Brian%20Kernighan">[1]</a>.
Studies suggest developers spend roughly <strong>50%</strong> of their time debugging
code<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=I%E2%80%99ve%20spent%20many%2C%20many%20hours,of%20our%20time%20debugging%20code">[2]</a>.
This guide will help you develop a systematic, senior-level thought
process for debugging tricky C++ issues – from single-threaded crashes
to complex multi-threaded bugs – so you can tackle problems
methodically and confidently.</p>

<h2 id="the-debuggers-mindset-think-like-a-detective">The Debugger’s Mindset: Think Like a Detective</h2>

<p>Debugging isn’t just about fixing a bug; it’s an investigation. You are
the detective trying to reconstruct what <em>really</em> happened in your
code<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=It%E2%80%99s%20tempting%20to%20think%20of,before%20committing%20to%20a%20solution">[3]</a>.
Adopting the right mindset is key:</p>

<ul>
  <li>
    <p><strong>Stay Calm and Systematic:</strong> When a mysterious crash or bug appears,
resist the urge to panic or apply random “fixes.” Instead, pause and
<strong>ask the critical question:</strong> <em>“What could actually cause this
behavior?”</em><a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=The%20Question%20That%20Separates%20Senior,I%20work%20with%20all%20think">[4]</a>.
This is the question senior engineers always start with. By first
mapping out possible root causes (e.g. <em>“Could it be a database lock?
A memory leak? A network timeout? A race condition?”</em>), you ensure you
understand the <em>problem</em> before attempting a
solution<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=The%20Question%20That%20Separates%20Senior,I%20work%20with%20all%20think">[4]</a>.
This upfront discipline might feel slower, but it dramatically cuts
down overall debugging time by focusing your efforts on likely
culprits rather than blind
guesses<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=me%3A%20System%20crashes%20%E2%86%92%20panic,I%20work%20with%20all%20think">[5]</a>.</p>
  </li>
  <li>
    <p><strong>Crashes Are Symptoms, Not Root Causes:</strong> A common rookie mistake is
to treat the line of code that crashed as the cause of the bug. In
reality, <strong>the crash is often just the last domino to
fall</strong><a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=have%20stuck%20with%20me%3A%201,%E2%80%9CIt%20works%20on%20my">[6]</a>.
For example, a segmentation fault might occur in function <code class="language-plaintext highlighter-rouge">foo()</code>, but
the true cause could be a buffer overflow or dangling pointer from
earlier in the program. As one seasoned engineer puts it: <em>“What you
see at the point of crash is often just the last domino. The real
cause usually lies 10 steps earlier – in an unchecked pointer, a
silent race, or a missed boundary condition. Don’t fix what</em> <em>crashed;
fix what</em> <em>led</em> <em>it
there.”</em><a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=have%20stuck%20with%20me%3A%201,%E2%80%9CIt%20works%20on%20my">[6]</a>.
In short, <strong>trace symptoms back to their root cause</strong> instead of
patching over the immediate error.</p>
  </li>
  <li>
    <p><strong>Embrace a Deep Understanding:</strong> Senior debuggers succeed because
they strive to <strong>think like the system</strong>, not just like the developer
who wrote the
code<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=production%20crashes%20changes%20you,friend%20%E2%80%94%20until%20it%E2%80%99s%20not">[7]</a>.
They consider how the program runs in real environments – with real
data, real workloads, and real timing. They know that <em>“It works on my
machine”</em> is never an excuse, because production may have different
memory pressure or thread scheduling that exposes issues hidden in
development<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=intent%2C%20not%20just%20data,Debugging%20production%20isn%E2%80%99t%20about">[8]</a>.
Always test under conditions that resemble the actual environment, so
you can catch bugs that only appear with realistic loads or
timing<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=intent%2C%20not%20just%20data,Debugging%20production%20isn%E2%80%99t%20about">[8]</a>.</p>
  </li>
  <li>
    <p><strong>Be Patient and Curious:</strong> Difficult bugs can be humbling – it often
takes time and iteration to uncover the
truth<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=production%20crashes%20changes%20you,friend%20%E2%80%94%20until%20it%E2%80%99s%20not">[7]</a>.
A senior engineer treats debugging as a learning opportunity and
remains curious about how the system got into its problematic state.
Rather than fearing weird crashes, learn to <strong>“respect the crash”</strong>
and use it as a clue to deepen your understanding of the
system<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=cleanup%20can%20surface%20bugs%20you%E2%80%99ll,CPlusPlus%20%20%2044">[9]</a>.
Patience and persistence are crucial; even the best engineers
encounter challenging bugs that require multiple attempts and
approaches to solve.</p>
  </li>
  <li>
    <p><strong>Use Evidence, Not Hunches (But Trust Instincts on Anomalies):</strong>
Effective debugging is driven by evidence. Collect as much information
as possible about the failure. That said, if something in the data or
behavior looks <em>odd</em> or out-of-place, trust your instincts and
investigate that
anomaly<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,The%20actual%20issue%20caused%20by">[10]</a>.
Often, <em>“if something looks weird it’s a good place to start your
investigation”</em><a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,code%20below%20%E2%80%94%20it%20should">[11]</a>.
For example, an unexpected null pointer, an unusual log message, or an
inconsistent variable value could be the breadcrumb that leads you to
the root cause. A disciplined investigator follows the evidence but
also knows when a “weird” clue might merit a closer look.</p>
  </li>
</ul>

<p>With the right mindset established, let’s outline a structured debugging
process that you can follow step by step.</p>

<h2 id="a-systematic-debugging-process">A Systematic Debugging Process</h2>

<p>Even the most complex bug can be conquered by breaking the debugging
process into clear steps. Think of it as applying the scientific method
to your code: observe, hypothesize, experiment, and
conclude<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=are%20possibly%20referring%20to%20what,that%20reproduces%20the%20problem%20reliably">[12]</a><a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=The%20situations%2C%20though%2C%20that%20I,follow%20steps%20along%20these%20lines">[13]</a>.
Here’s a systematic approach that many experienced engineers use:</p>

<ol>
  <li>
    <p><strong>Gather Information &amp; Reproduce the Problem:</strong> First, collect all
available clues about the bug. What exactly is the observed issue
(crash, incorrect output, hang, etc.)? <strong>Check logs, error messages,
stack traces, and core dumps</strong> for any
hints<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=,at%20what%20it%20tells%20you">[14]</a>.
Talk to the user or tester who reported it – what were they doing
when it happened? Can you <strong>reproduce the issue reliably</strong> (or at
least occasionally) in a controlled environment? If possible, come
up with a minimal set of steps or inputs that trigger the bug.
During this phase, perform both <strong>narrow observation</strong> and <strong>wide
observation</strong><a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=,at%20what%20it%20tells%20you">[14]</a><a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=,yourself%20what%20that%20could%20mean">[15]</a>.
The narrow view focuses on the immediate context of the failure: the
function call stack at the crash, values of local variables, and the
code around the failure
point<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=,at%20what%20it%20tells%20you">[14]</a>.
The wide view looks at the broader system state: What are other
threads or modules doing? Is memory or CPU usage unusual? Did the
issue occur under certain external conditions (time of day, high
load, specific
configuration)<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=,yourself%20what%20that%20could%20mean">[15]</a>?
This comprehensive fact-gathering is critical. It prevents wild
goose chases by grounding your investigation in reality. Often, just
reproducing and observing the problem closely will already shrink
the list of possible causes.</p>
  </li>
  <li>
    <p><strong>Form a Hypothesis (Theorize Potential Causes):</strong> Based on the
evidence, <strong>develop one or more theories</strong> about what might be
causing the
issue<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,If%20you%E2%80%99ve">[16]</a>.
Ask yourself: <em>“Given what I know so far, what are the most likely
explanations?”</em> For example, if the program crashes when handling a
certain input, could there be a bug in how that input is parsed
(e.g. a null pointer or division by
zero)<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=Hypothesis%3A%20I%20think%20that%20the,a%20division%20by%20zero%20error">[17]</a>?
If threads deadlock when under heavy load, perhaps a mutex is not
acquired in a consistent order. <strong>Draw on your knowledge of the code
and common bug patterns in C++</strong>. Memory-related errors (like buffer
overflows or use-after-free) often result in crashes at a distance
from the real
mistake<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=have%20stuck%20with%20me%3A%201,Lesson%3A%20Don%E2%80%99t%20fix%20what">[18]</a>.
Concurrency issues often manifest as intermittent hangs or data
corruption. List a few plausible causes – and also list what
<em>doesn’t</em> fit. Eliminating impossible or unrelated factors can
narrow your focus (recall Sherlock Holmes’ adage about eliminating
the
impossible)<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=examination%20in%20the%20previous%20steps,after%20you%20eliminate%20the%20impossible">[19]</a>.
A senior engineer will <strong>explicitly enumerate assumptions</strong> and
verify them one by
one<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=2">[20]</a><a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=Debugging%20is%20fundamentally%20a%20testing,those%20assumptions%20can%20be%20incorrect">[21]</a>.
For example, <em>“I assume function X is always setting that pointer.
Could it ever be null?”</em> Writing down these assumptions or expected
behaviors can highlight gaps in your understanding. In fact,
techniques like behavior-driven development (BDD) are essentially
ways of formalizing assumptions and expected
outcomes<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=BDD%20is%20a%20great%20tool,here">[22]</a><a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=1,At%20that%20point%2C%20you">[23]</a>.
The key is to <strong>hypothesize rationally, not randomly</strong>. Use the
clues from step 1 to guide your theory. You might come up with
multiple hypotheses; prioritize them by likelihood and potential
impact.</p>
  </li>
  <li>
    <p><strong>Test Your Hypothesis (Experiment and Observe):</strong> Now, treat your
hypothesis like a scientific theory – put it to the
test<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,and%20form%20a%20new%20hypothesis">[24]</a>.
This often means <strong>reproducing the bug under controlled conditions</strong>
to see if the hypothesis holds true. If you suspect a certain
function is causing a crash, set breakpoints or add logging around
that area and re-run the program. If you think a race condition
might be the culprit, try to force the timing that would trigger it.
For example, one engineer suspected a race condition was behind a
crash, so he <strong>inserted a deliberate short delay</strong> (<code class="language-plaintext highlighter-rouge">Sleep(500)</code>) at
a strategic point in the code to give another thread time to “do its
bad stuff at the right time” – and the bug manifested
reliably<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=previous%20step%2C%20this%20should%20be,in%20code%20that%20you%20own">[25]</a>.
This confirmed the race condition hypothesis. You can use many forms
of experiments:</p>
  </li>
  <li>
    <p><strong>Interactive Debugging:</strong> Run the program in a debugger, step
through the code, and watch the state. Inspect variables and program
flow to see where things go awry. Modern IDEs let you break at
certain conditions, watch variables, and even modify values at
runtime to test theories. Remember, though, that <strong>in multi-threaded
programs a debugger can disturb timing</strong> – pausing all threads at a
breakpoint might make a race condition or deadlock
disappear<a href="https://medium.com/javarevisited/debugging-deadlocks-and-race-conditions-8d184525a1fd#:~:text=This%20sounds%20complicated%2C%20but%20it,won%E2%80%99t%20see%20the%20problem%20occurring">[26]</a><a href="https://medium.com/javarevisited/debugging-deadlocks-and-race-conditions-8d184525a1fd#:~:text=debugging%20tools%20for%20a%20deadlock,won%E2%80%99t%20see%20the%20problem%20occurring">[27]</a>.
Use breakpoints wisely (or use non-intrusive logging breakpoints
that don’t suspend execution) when dealing with concurrency.</p>
  </li>
  <li>
    <p><strong>Logging and Tracing:</strong> Insert temporary log statements to print
key variable values or execution milestones (e.g., <em>“Reached point
A”</em>, <em>“Value of X = ...”</em>). Logging is often a lifesaver,
especially in production where you can’t attach a
debugger<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=domino%20to%20fall,%E2%80%9CIt%20works%20on%20my">[28]</a>.
Good logs can narrate what the code was doing leading up to the
issue. However, <strong>avoid excessive or low-quality logs</strong> – too much
noise can obscure the
truth<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=crashed%3B%20fix%20what%20led%20it,%E2%80%9CIt%20works%20on%20my">[29]</a>.
Log <strong>intent, not just
data</strong><a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=crashed%3B%20fix%20what%20led%20it,%E2%80%9CIt%20works%20on%20my">[29]</a>.
For example, a log that explains <em>why</em> a code path was taken
(“Allocating buffer of size N for user input”) is more helpful than
dozens of logs just printing variable values with no context. In
concurrent programs, also beware that adding logs can <strong>change the
timing</strong> and hide the bug (a classic <em>Heisenbug</em>
scenario)<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=It%E2%80%99s%20common%20to%20see%20engineers,clue%20about%20the%20underlying%20cause">[30]</a><a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=the%20mischievous%20bug%20in%20action,clue%20about%20the%20underlying%20cause">[31]</a>.
If you suspect this, consider logging to an in-memory buffer or
using a trace that minimally interferes with thread scheduling.</p>
  </li>
  <li>
    <p><strong>Write a Targeted Test Case:</strong> If possible, write a small unit test
or driver program that triggers the bug
reliably<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=%2B25">[32]</a>.
This is like <strong>trapping the bug in a jar</strong>. Having an isolated,
repeatable test is immensely valuable – it not only helps you
confirm the bug and fix, but also prevents it from sneaking back
(you can add the test to your regression
suite)<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=%2B25">[33]</a><a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=If%20you%20succeed%20in%20reproducing,amount%20of%20design%20and%20review">[34]</a>.
Sometimes the very act of writing a test can reveal the problem
(e.g., you realize a certain input was never handled). If the bug is
hard to reproduce normally, you might “cheat” by modifying the code
or environment to provoke it (as in the earlier Sleep example, or by
running a loop a thousand times to increase the odds of a race
condition
occurring)<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=previous%20step%2C%20this%20should%20be,in%20code%20that%20you%20own">[35]</a>.
These <strong>controlled experiments</strong> are the heart of debugging – they
prove or disprove your hypotheses.</p>
  </li>
</ol>

<p>After running a test, <strong>observe the outcome</strong>. Did it confirm your
hypothesis or not? If yes, you’ve likely identified the right area or
cause. If not, don’t be discouraged – debugging is iterative. Go back
to step 2: form a new hypothesis consistent with the new information
you’ve gathered, and test again. Each experiment, whether it fails or
succeeds, teaches you something and narrows the search. The process
repeats until you pinpoint the bug.</p>

<ol>
  <li><strong>Identify the Root Cause and Fix It:</strong> Eventually, your experiments
will lead you to the <strong>root cause</strong> – the specific mistake in code
or design that is responsible. This might be a null pointer
dereference, an off-by-one loop index causing buffer overflow, a
missing lock around a shared resource, etc. It’s important at this
stage to <strong>verify that this root cause truly explains the observed
problem</strong> (and doesn’t just paper over the symptom). A senior
engineer reminds themselves: <em>fix the cause, not just the symptom</em>.
For instance, if a crash happened due to a null pointer, the real
fix might be ensuring that pointer is initialized or validated much
earlier, rather than just adding a null-check right before the crash
site. Take a moment to consider <em>why</em> the bug happened and how to
prevent similar issues. Now devise a fix or solution:</li>
  <li><strong>Implement the Fix Carefully:</strong> Write the code change to address
the root cause. In C++, this might involve adding a missing check,
correcting a misuse of an API, adjusting thread synchronization,
etc. Simpler bugs will have straightforward fixes, whereas complex
issues (like redesigning a locking scheme) might require more
thought. It can help to review the fix with a colleague or run
additional tests.</li>
  <li><strong>Test the Fix Under Realistic Conditions:</strong> Rerun the program (and
the test case from step 3, if you created one) under the same
conditions that originally triggered the bug. Ensure the issue is
truly resolved and that you didn’t introduce new problems. For
tricky concurrency or memory issues, consider testing under a
variety of scenarios (different optimization levels, high load,
etc.) to be confident the fix holds water.</li>
  <li><strong>Regression Safety:</strong> Incorporate a regression test if possible
(e.g., the unit test you wrote or a new one) so that this same bug
doesn’t resurface later
unnoticed<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=%2B25">[32]</a>.
Many seasoned developers practice “find a bug, write a test” –
every time a bug is found, it’s an opportunity to strengthen the
test
suite<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=%2B25">[33]</a>.</li>
  <li><strong>Learn and Log Knowledge:</strong> Finally, take note of what went wrong
and why. This could mean adding a comment in code, improving logging
around that area for future diagnostics, or sharing a brief
post-mortem with your team. Each debugging session is a chance to
improve coding practices or monitoring so that similar bugs are
caught earlier or prevented entirely.</li>
</ol>

<p>Throughout this process, <strong>maintain a feedback loop</strong>. If your
hypothesis was wrong, revisit the clues and form a new theory. If an
experiment’s results are confusing, gather more data (add more logging,
inspect memory, etc.). Systematic debugging is inherently iterative –
each cycle brings you closer to the answer.</p>

<p>Also, remember the human aspect: debugging can be mentally exhausting,
especially after hours of chasing a bug. Don’t hesitate to <strong>use fresh
eyes</strong> – discuss the problem with a teammate or even explain it to a
rubber duck. The act of articulating the problem often reveals something
you overlooked. In fact, “rubber duck debugging,” where you narrate your
code logic to an inanimate object, is a tried-and-true technique to find
hidden assumptions or
mistakes<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=3">[36]</a>.
And if you’re really stuck, sometimes the best trick is to <strong>step away
for a short break</strong>. Go for a walk or grab a coffee – letting your
brain rest can break the tunnel vision and suddenly the solution clicks
into
place<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=5,outside">[37]</a><a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=To%20get%20away%20from%20this%2C,the%20most%20underutilized%20debugging%20skills">[38]</a>.</p>

<p>In summary, approach debugging as a disciplined, evidence-based process.
By methodically gathering information, hypothesizing, testing, and
iterating, you can crack even the toughest bugs. Now, let’s delve into
specific challenges you’ll face in C++ debugging – particularly with
memory errors and multi-threaded issues – and how to handle them.</p>

<h2 id="debugging-memory-bugs-and-crashes-single-threaded-issues">Debugging Memory Bugs and Crashes (Single-Threaded Issues)</h2>

<p>C++ gives you powerful control over memory, which unfortunately means
memory bugs are a common source of “tricky” problems. These bugs can
cause crashes, data corruption, or bizarre behavior that defies initial
explanation. Here are key considerations and techniques for handling
memory-related issues:</p>

<ul>
  <li>
    <p><strong>Recognize the Symptoms:</strong> Memory errors often manifest as
<strong>segmentation faults, access violations, or corrupted data</strong>. A
telltale sign is a crash that occurs at a location that <em>should</em> be
perfectly valid, or a variable mysteriously changing to an impossible
value. For example, using an uninitialized pointer can sometimes crash
far from the point of error, making it hard to connect cause and
effect. <strong>Uninitialized variables</strong> in particular are a notorious
source of headaches – they can produce different behavior in debug vs
release builds (e.g., a program that only crashes in Release mode but
seems fine in
Debug)<a href="https://www.reddit.com/r/cpp/comments/1iqoaa7/professional_programmers_what_are_some_of_the/#:~:text=%E2%80%A2%20%201y%20ago">[39]</a>.
This is because some compilers fill uninitialized memory with known
patterns in Debug, masking the bug, whereas in Release the memory
contains random
garbage<a href="https://www.reddit.com/r/cpp/comments/1iqoaa7/professional_programmers_what_are_some_of_the/#:~:text=%E2%80%A2%20%201y%20ago">[39]</a>.
If you encounter a bug that only appears under optimization or on
certain platforms, <strong>suspect issues like uninitialized memory or
undefined behavior</strong>.</p>
  </li>
  <li>
    <p><strong>Use the Clues in a Crash Dump or Error Message:</strong> When a crash
happens, <em>what</em> exactly crashed? Note the instruction pointer or stack
trace at the moment of failure. In C++ on Linux, you might get a core
dump; on Windows an error dialog or event log. Load these in a
debugger to inspect the call stack and memory around the crash.
<strong>Examine local variables and pointers</strong> – often you’ll find
something like an address <code class="language-plaintext highlighter-rouge">0xCCCCCCCC</code> or <code class="language-plaintext highlighter-rouge">0xdeadbeef</code> (on Windows,
indicative of an uninitialized or freed pointer), or an obviously
incorrect value. This is the “narrow observation” at
work<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=,at%20what%20it%20tells%20you">[14]</a>.
But remember, as discussed, the crash point is likely a symptom. If
the stack trace shows a crash in <code class="language-plaintext highlighter-rouge">free()</code> or <code class="language-plaintext highlighter-rouge">delete</code>, it likely means
memory corruption happened earlier (writing past array bounds or
double-freeing memory). In such cases, use the crash info as a
starting point and then <strong>trace backwards</strong>. Ask: “How could this
pointer have become invalid? Where was it last modified? Could there
be a path that forgot to allocate it, or freed it too early?” Logging
the lifecycle of suspicious objects (allocations and deallocations)
can shed light on misuse.</p>
  </li>
  <li>
    <p><strong>Isolate and Reproduce Memory Issues:</strong> If the bug is
timing-insensitive (purely in one thread), try to narrow down the code
that triggers it. For instance, if you suspect a particular function
corrupts memory, call it in a simple test harness with the same
inputs. Use tools to help – <strong>memory debugging tools</strong> can be
invaluable. Instruments like <em>Valgrind, AddressSanitizer (ASan), or
Purify</em> can detect common memory errors by running your program in a
special instrumented
mode<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=Try%20to%20reduce%20the%20test,that%20is%20causing%20the%20problem">[40]</a>.
They can catch out-of-bounds accesses, use-after-free, double deletes,
and so on, at the moment they occur. If you have a crash and suspect a
memory bug, running the program under Valgrind (or ASan, which is
built into modern compilers) often pinpoints the real culprit line of
code with a clear error message. This is a general piece of advice:
<strong>use the right tools for the job</strong>. It’s not “cheating” – even
senior engineers rely on memory checkers to save time and sanity.</p>
  </li>
  <li>
    <p><strong>Beware of Silent Failures:</strong> One especially tricky scenario is when
the program <strong>fails later than the original error</strong>. For example,
consider code that catches an exception but does nothing and continues
running in a bad
state<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,The%20actual%20issue%20caused%20by">[10]</a>.
The actual error gets swallowed, and only much later does something
else blow up due to that. C++ code that overly uses
<code class="language-plaintext highlighter-rouge">catch (...) { /* ignore */ }</code> or ignores error return codes can
produce bugs that seem magical. A senior debugging approach is to
<strong>audit the code for any place errors might be hidden</strong>. If you see a
catch block that logs nothing or a function that returns an error code
that no one checks, consider enabling logging or assertions
there<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,The%20actual%20issue%20caused%20by">[10]</a>.
Often, making the program <em>fail earlier</em> (at the real cause) by not
suppressing errors will drastically simplify your debugging. In
essence, <strong>fail fast</strong> and loud, so you’re not searching for a needle
in a haystack of secondary failures.</p>
  </li>
  <li>
    <p><strong>Understand C++ Specifics:</strong> Knowing C++ internals helps in
debugging. For instance, memory layout (stack vs heap, static vs
dynamic allocation) can hint at why a certain address is crashing. A
crash at an address like <code class="language-plaintext highlighter-rouge">0x00000010</code> is often a null pointer offset
(nullptr + 0x10), meaning an object’s base pointer was null.
Corruption patterns like <code class="language-plaintext highlighter-rouge">0xFEEEFEEE</code> (on Windows) or <code class="language-plaintext highlighter-rouge">0xABABABAB</code>
might indicate memory that was freed or is uninitialized (these are
special fill patterns in debug modes). Recognizing these can point you
to the nature of the bug (e.g., use-after-free). Additionally, keep in
mind object lifetimes in C++: a common bug is using an object after it
went out of scope or was moved. If a crash happens during object
destruction, perhaps something already deleted it or corrupted its
vtable. <strong>Leverage assertions</strong> in your C++ code as proactive
debugging aids – for example, <code class="language-plaintext highlighter-rouge">assert(ptr != nullptr)</code> at critical
points, or runtime sanity checks for data structure invariants. These
can catch issues closer to their source.</p>
  </li>
</ul>

<p>When you fix a memory bug, you’ll not only solve the immediate crash but
also improve the overall stability of your program. Always reflect:
could similar code elsewhere have the same bug? This is how a senior
engineer prevents the next bug – by generalizing the lesson learned
(e.g., “We should use std::vector instead of new[] to avoid manual
memory errors” or “We need a safer string copy function throughout the
codebase.”).</p>

<h2 id="debugging-concurrency-issues-multi-threaded-problems">Debugging Concurrency Issues (Multi-Threaded Problems)</h2>

<p>Multi-threaded C++ programs introduce a whole new class of bugs that
stem from concurrency: <strong>race conditions, deadlocks, livelocks,
atomicity violations</strong>, and so on. These are often the <em>trickiest</em>
problems because they are <strong>non-deterministic</strong> – the bug might vanish
when you try to observe it, or only occur once in a blue moon under
specific conditions. Debugging concurrent issues requires a slightly
different strategy, though it builds on the same principles we’ve
covered. Here’s how to approach multi-threaded debugging:</p>

<ul>
  <li>
    <p><strong>Recognize Concurrency Bug Symptoms:</strong> Concurrency bugs often appear
as <strong>random, intermittent failures</strong>. You might see data that is
occasionally incorrect, or a crash that happens only under heavy load
or on specific hardware. A classic sign is, <em>“It works on my machine,
but not on the server,”</em> or <em>“We only see this issue once a week.”</em> As
one engineer quipped, <em>“If it doesn't happen on every machine, it's
probably a form of race condition or threading
issue.”</em><a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=2,good%20tools%20gets%20this%20done">[41]</a>.
In multithreaded apps, you may also encounter <strong>deadlocks</strong> (the
program just hangs, with two or more threads stuck waiting on each
other) or <strong>high CPU spin</strong> (threads stuck in a livelock). Memory
ordering bugs might produce <em>flaky tests</em> that pass or fail
unpredictably. The first step is acknowledging you likely have a
concurrency issue when you see nondeterministic behavior. Don’t
dismiss a bug that “goes away when you add logging” – that’s a red
flag pointing to a timing-sensitive race
condition<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=It%E2%80%99s%20common%20to%20see%20engineers,clue%20about%20the%20underlying%20cause">[30]</a>.</p>
  </li>
  <li>
    <p><strong>Make the Bug Appear More Reliably:</strong> Debugging a race or deadlock
starts with getting it to show itself more often. Use <strong>input
variation and timing manipulation</strong> to your
advantage<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=By%20manipulating%20input%20data%20and,that%20would%20otherwise%20remain%20undetected">[42]</a>.
For example, try running the program on more CPU cores or with a
heavier workload to stress timing. Sometimes adding a deliberate
slight delay or sleep in one thread can make a latent bug manifest
(similar to how we injected a <code class="language-plaintext highlighter-rouge">Sleep</code> earlier to catch a
race)<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=previous%20step%2C%20this%20should%20be,in%20code%20that%20you%20own">[25]</a>.
Conversely, you might run the program in a tight loop or with random
thread scheduling (some testing frameworks or tools can introduce
randomness) to increase the chances of hitting the problematic
interleaving of events. Another trick is to use different builds –
e.g., if it fails in Release but not Debug, try to pinpoint what
timing or optimization differences are affecting it. The goal is to
find a semi-reliable way to trigger the issue, which is half the
battle in debugging concurrency.</p>
  </li>
  <li>
    <p><strong>Leverage Tools for Concurrency:</strong> Just as we have memory analyzers,
we have <strong>concurrency analyzers</strong>. Tools like <em>ThreadSanitizer (TSan)</em>
can detect data races by instrumenting memory accesses at runtime, and
<em>Helgrind</em> (part of Valgrind) can also catch certain locking
issues<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=,Blog">[43]</a>.
If your code is portable and you can run it under such tools
(typically in tests), they might immediately flag a race condition and
point to the two threads and variables involved. Static analysis tools
can also sometimes warn about missing locks or potential deadlocks.
While these tools are not foolproof and can produce false positives or
be heavy to run, they are worth considering for gnarly bugs. Using
them is conceptually similar to using a net to catch the phantom –
they might observe an invalid concurrent access that you can’t easily
catch by eye. Keep in mind though, some complex concurrency issues
(especially involving misuse of memory ordering or atomic operations)
might not be caught by standard tools, so manual reasoning is often
needed in tandem.</p>
  </li>
  <li>
    <p><strong>Inspect Thread States for Deadlocks:</strong> When facing a deadlock (your
program just freezes), a powerful technique is to <strong>capture a snapshot
of all threads’ call stacks</strong>. In practice, this means if you notice
the program hung, attach a debugger or use an OS tool to pause it. In
a debugger like GDB, you can use <code class="language-plaintext highlighter-rouge">info threads</code> and then switch to
each thread to see where it’s stuck, or use <code class="language-plaintext highlighter-rouge">thread apply all bt</code> to
get backtraces of all
threads<a href="https://stackoverflow.com/questions/1506131/how-to-debug-a-multithreaded-application-in-c-which-is-hung-deadlock#:~:text=The%20magic%20invocation%20in%20gdb,is">[44]</a>.
On Windows, you might use Visual Studio’s debugger or a dump file and
view all threads. Look at the stack traces: if you see two threads
each waiting for a lock the other holds (for example, Thread A’s stack
shows it’s waiting on a mutex that Thread B has, and vice versa),
you’ve identified a deadlock cycle. Many debuggers will even indicate
when a thread is blocked on a synchronization primitive. By examining
locks or condition variables in the debugger, you can infer which
resource is contested. This process — <em>pausing and peeking at thread
states</em> — is often the only way to diagnose a deadlock, since adding
logging or breakpoints might interfere with the timing. The good news
is that once you can see the threads’ states, deadlocks tend to be
obvious (e.g., each thread’s stack will show it waiting to acquire a
lock that the other thread holds). The fix then involves changing the
locking order or using finer-grained locks, etc., but the detective
work is in finding that cycle.</p>
  </li>
  <li>
    <p><strong>Tackle Race Conditions Systematically:</strong> <strong>Data races</strong> (where two
threads access the same data without proper synchronization, and at
least one is a write) are insidious because they may not crash
immediately – they just produce wrong results or corrupt data
occasionally. To catch races, you need to trace how data is shared.
Logs can help if used smartly: for example, you can log every time a
certain variable is written along with the current thread ID. If in
the logs you see an unexpected interleaving (e.g., two threads writing
to a variable “out of order”), that’s evidence of a race. However, as
mentioned, <em>logging itself can perturb
timing</em><a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=It%E2%80%99s%20common%20to%20see%20engineers,clue%20about%20the%20underlying%20cause">[45]</a>.
One advanced technique is using <strong>tracepoints or conditional logging</strong>
that doesn’t fully stop threads. For instance, some debuggers allow
“non-suspending breakpoints” that just print a message. This can let
the program run at near full speed while tracing events. In one
approach, a developer set up tracepoints on a function’s entry and
exit to log thread IDs, then looked for anomalies in the sequence
(like seeing two “enter” logs in a row from different threads without
an “exit,” indicating one thread was interrupted mid-function by
another – a clue of unsynchronized
access)<a href="https://medium.com/javarevisited/debugging-deadlocks-and-race-conditions-8d184525a1fd#:~:text=Again%2C%20we%20don%E2%80%99t%20suspend%20the,disturbed%20by%20the%20debugging%20process">[46]</a><a href="https://medium.com/javarevisited/debugging-deadlocks-and-race-conditions-8d184525a1fd#:~:text=TL%3BDR">[47]</a>.
Another helpful strategy is <strong>randomized testing</strong> – running the
program with varied thread schedules or using stress-test harnesses
that launch threads in random
orders<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=Randomized%20testing">[48]</a>.
Over many runs, this may produce the race condition at least once,
giving you an opportunity to catch it in the act (or at least in the
logs). Once you have an idea of two operations that shouldn’t coincide
but did, you’ve found the race. Then you can proceed to fix it by
adding proper mutexes, atomics, or other synchronization to ensure
those operations cannot overlap incorrectly.</p>
  </li>
  <li>
    <p><strong>Heuristic and Intuition:</strong> Debugging concurrency often involves a
bit of art in addition to science. Seasoned engineers draw on
experience to guess where a race might be. Common pitfalls to
consider: <strong>shared global variables</strong> or singletons, unsynchronized
access to data structures, misuse of thread-unsafe APIs, and
order-of-initialization issues (especially in C++ with static
objects). If a bug only appears under heavy load, suspect a race
condition or resource contention. If it appears after a consistent
time, maybe a thread is starving or blocked (a form of deadlock or
starvation). One senior C++ engineer described that logging alone
often isn’t enough for these issues, and that’s precisely why such
problems get escalated to “senior developers” to
solve<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=A%20senior%20C%2B%2B%20developer%20consultant,told%20a%20colleague%20of%20mine">[49]</a>.
They need to <strong>combine tools with deep knowledge of the code’s
design</strong>. Don’t be afraid to brainstorm possible thread interleavings
and see if any could produce the observed effect. Draw a timeline of
thread actions if needed. By mapping out “Thread A does X, Thread B
does Y,” you might spot the gap where the bug slips in.</p>
  </li>
  <li>
    <p><strong>Apply Fixes and Test Thoroughly:</strong> Once you think you’ve cornered
the bug, apply a fix and test rigorously. For concurrency fixes, it’s
wise to run extended tests or soak tests, because timing issues might
not surface immediately. Also be mindful that fixes like adding locks
can introduce performance hits or even new deadlocks if not done
carefully, so code review and consideration of the design is
important. After fixing, use the same scenario that reproduced the bug
before to confirm it’s gone. If you had logging or a test case, they
should now show no anomalies.</p>
  </li>
</ul>

<p>Debugging multi-threaded issues is challenging, but it’s also very
rewarding – it forces you to understand your system at a deep level.
Over time, you’ll start <strong>anticipating where concurrency problems might
arise</strong> and prevent them with better design (for example, using
thread-safe queues, avoiding shared state when possible, etc.). And when
a heisenbug does land on your desk at 2 AM, you’ll know how to
methodically approach it without desperation.</p>

<h2 id="conclusion-practice-and-perseverance">Conclusion: Practice and Perseverance</h2>

<p>Becoming proficient at debugging complex C++ issues is a journey. This
guide has outlined the mindset and process that senior engineers use:
<strong>stay analytical, gather evidence, think in hypotheses, and iterate
systematically</strong>. We’ve also covered special considerations for memory
corruption and concurrency, which are among the most daunting bugs
you’ll face.</p>

<p>Remember that each bug you tackle will strengthen your debugging
muscles. Over time, patterns will emerge – you’ll fix a bug and recall
a similar scenario months later, and the solution will come that much
quicker. The difference between a junior and senior debugger often comes
down to experience: senior engineers have seen more failures and thus
have a mental checklist of “what could go wrong.” By following a
disciplined approach, you are essentially building your own experience
playbook. Even without decades of practice, you can debug “like a pro”
by emulating the pros’ thought process.</p>

<p>A few final tips to leave you with:</p>

<ul>
  <li>
    <p><strong>Don’t Panic, Don’t Give Up:</strong> Complex bugs can be frustrating, but
keep chipping away. Take breaks when needed, seek a second opinion for
fresh perspectives, and maintain confidence that there <em>is</em> a logical
explanation waiting to be found. As one source puts it, <em>“the next
time you run into a problem, don’t panic – just remember to be
methodical, focused, and relaxed. You’ve got
this.”</em><a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=Now%20you%20know%20what%20to,do">[50]</a><a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=solution%20is%20hard%20to%20beat,You%E2%80%99ve%20got%20this">[51]</a>.</p>
  </li>
  <li>
    <p><strong>Continuously Improve Your Toolkit:</strong> While this guide focused on
conceptual process over specific tools, be aware of the debugging
tools at your disposal and practice using them in low-stakes
situations. Learn your IDE’s debugger features, try out Valgrind or
AddressSanitizer on test programs, explore logging frameworks, etc.
The better you know your tools, the more effectively you can
investigate issues. Tools won’t <em>solve</em> the bug for you, but they
amplify your abilities as an
investigator<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=1">[52]</a><a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=pattern%20is%20good%2C%20but%20it%E2%80%99s,programming%2C%20this%20tool%20is%20indispensable">[53]</a>.</p>
  </li>
  <li>
    <p><strong>Learn from Each Bug:</strong> After fixing a tricky bug, reflect on how it
could have been prevented or diagnosed faster. Maybe you realize a
certain unit test would have caught it earlier – go ahead and write
that test now. Maybe better logging or an assertion would have made
the bug obvious – implement those improvements. Over time, your
codebase will become more robust, and the frequency of “weird” bugs
will diminish. But new challenges will always arise, and your growing
experience will prepare you for them.</p>
  </li>
</ul>

<p>By understanding the <em>process</em> of debugging, you empower yourself to
tackle problems that once seemed “magic” or unsolvable. Debugging is as
much about mindset and strategy as it is about technical knowledge.
Approach it with curiosity and rigor, and you’ll not only fix the bug at
hand but also become a better engineer in the process. Happy debugging!</p>

<p><strong>Sources:</strong></p>

<ul>
  <li>
    <p>R. Nel, “Crushing Bugs: A Developer’s Guide to Debugging Like a Pro.”
<em>Medium</em> (2023).
<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,If%20you%E2%80%99ve">[16]</a><a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,The%20actual%20issue%20caused%20by">[10]</a></p>
  </li>
  <li>
    <p>S. Nagdive et al., <em>LinkedIn Posts on Debugging Mindset &amp; Lessons
Learned</em> (2023).
<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=have%20stuck%20with%20me%3A%201,%E2%80%9CIt%20works%20on%20my">[6]</a><a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=The%20Question%20That%20Separates%20Senior,I%20work%20with%20all%20think">[4]</a></p>
  </li>
  <li>
    <p>M. Wilkins, <em>Software Engineering StackExchange – Debugging Process
Answer</em> (2011).
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=,in%20code%20that%20you%20own">[54]</a><a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=,at%20what%20it%20tells%20you">[14]</a></p>
  </li>
  <li>
    <p>“Debugging concurrency bugs in multithreaded applications.” <em>Undo
Blog</em> (n.d.).
<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=They%20are%20difficult%20to%20catch,load%2C%20the%20bug%20may%20appear">[55]</a><a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=It%E2%80%99s%20common%20to%20see%20engineers,clue%20about%20the%20underlying%20cause">[30]</a></p>
  </li>
  <li>
    <p><em>Stack Overflow discussion on multithreaded debugging</em> (2009).
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=2,good%20tools%20gets%20this%20done">[41]</a></p>
  </li>
  <li>
    <p>Coralogix Team, “Five Tricks That Senior Engineers Use When They’re
Debugging.” <em>Coralogix Blog</em> (2022).
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=To%20get%20away%20from%20this%2C,the%20most%20underutilized%20debugging%20skills">[38]</a><a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=Now%20you%20know%20what%20to,do">[56]</a></p>
  </li>
  <li>
    <p>Reddit r/cpp discussion, “Common C++ Debugging Errors” (2023).
<a href="https://www.reddit.com/r/cpp/comments/1iqoaa7/professional_programmers_what_are_some_of_the/#:~:text=%E2%80%A2%20%201y%20ago">[39]</a></p>
  </li>
</ul>

<hr />

<p><a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,%E2%80%95%20Brian%20Kernighan">[1]</a>
<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=I%E2%80%99ve%20spent%20many%2C%20many%20hours,of%20our%20time%20debugging%20code">[2]</a>
<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,The%20actual%20issue%20caused%20by">[10]</a>
<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,code%20below%20%E2%80%94%20it%20should">[11]</a>
<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,If%20you%E2%80%99ve">[16]</a>
<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=Hypothesis%3A%20I%20think%20that%20the,a%20division%20by%20zero%20error">[17]</a>
<a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc#:~:text=,and%20form%20a%20new%20hypothesis">[24]</a>
Crushing Bugs: A Developer’s Guide to Debugging Like a Pro | by Riaan
Nel | Medium</p>

<p><a href="https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc">https://medium.com/@riaanfnel/crushing-bugs-a-developers-guide-to-debugging-like-a-pro-d673906ae0dc</a></p>

<p><a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=It%E2%80%99s%20tempting%20to%20think%20of,before%20committing%20to%20a%20solution">[3]</a>
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=2">[20]</a>
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=Debugging%20is%20fundamentally%20a%20testing,those%20assumptions%20can%20be%20incorrect">[21]</a>
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=BDD%20is%20a%20great%20tool,here">[22]</a>
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=1,At%20that%20point%2C%20you">[23]</a>
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=3">[36]</a>
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=5,outside">[37]</a>
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=To%20get%20away%20from%20this%2C,the%20most%20underutilized%20debugging%20skills">[38]</a>
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=Now%20you%20know%20what%20to,do">[50]</a>
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=solution%20is%20hard%20to%20beat,You%E2%80%99ve%20got%20this">[51]</a>
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=1">[52]</a>
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=pattern%20is%20good%2C%20but%20it%E2%80%99s,programming%2C%20this%20tool%20is%20indispensable">[53]</a>
<a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/#:~:text=Now%20you%20know%20what%20to,do">[56]</a>
Five Tricks Senior Engineers Use When Debugging - Coralogix</p>

<p><a href="https://coralogix.com/blog/debugging-tricks-senior-engineers/">https://coralogix.com/blog/debugging-tricks-senior-engineers/</a></p>

<p><a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=The%20Question%20That%20Separates%20Senior,I%20work%20with%20all%20think">[4]</a>
<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=me%3A%20System%20crashes%20%E2%86%92%20panic,I%20work%20with%20all%20think">[5]</a>
<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=have%20stuck%20with%20me%3A%201,%E2%80%9CIt%20works%20on%20my">[6]</a>
<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=production%20crashes%20changes%20you,friend%20%E2%80%94%20until%20it%E2%80%99s%20not">[7]</a>
<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=intent%2C%20not%20just%20data,Debugging%20production%20isn%E2%80%99t%20about">[8]</a>
<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=cleanup%20can%20surface%20bugs%20you%E2%80%99ll,CPlusPlus%20%20%2044">[9]</a>
<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=have%20stuck%20with%20me%3A%201,Lesson%3A%20Don%E2%80%99t%20fix%20what">[18]</a>
<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=domino%20to%20fall,%E2%80%9CIt%20works%20on%20my">[28]</a>
<a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR#:~:text=crashed%3B%20fix%20what%20led%20it,%E2%80%9CIt%20works%20on%20my">[29]</a>
From 6 hours to insight: how debugging teaches systems thinking |
Shireen Nagdive posted on the topic | LinkedIn</p>

<p><a href="https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR">https://www.linkedin.com/posts/shireennagdive_softwarengineering-activity-7386054197181476864--KPR</a></p>

<p><a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=are%20possibly%20referring%20to%20what,that%20reproduces%20the%20problem%20reliably">[12]</a>
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=The%20situations%2C%20though%2C%20that%20I,follow%20steps%20along%20these%20lines">[13]</a>
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=,at%20what%20it%20tells%20you">[14]</a>
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=,yourself%20what%20that%20could%20mean">[15]</a>
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=examination%20in%20the%20previous%20steps,after%20you%20eliminate%20the%20impossible">[19]</a>
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=previous%20step%2C%20this%20should%20be,in%20code%20that%20you%20own">[25]</a>
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=%2B25">[32]</a>
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=%2B25">[33]</a>
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=If%20you%20succeed%20in%20reproducing,amount%20of%20design%20and%20review">[34]</a>
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=previous%20step%2C%20this%20should%20be,in%20code%20that%20you%20own">[35]</a>
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=Try%20to%20reduce%20the%20test,that%20is%20causing%20the%20problem">[40]</a>
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=2,good%20tools%20gets%20this%20done">[41]</a>
<a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi#:~:text=,in%20code%20that%20you%20own">[54]</a>
debugging - What process do you normally use when attempting to debug a
problem/issue/bug with your software? - Software Engineering Stack
Exchange</p>

<p><a href="https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi">https://softwareengineering.stackexchange.com/questions/37242/what-process-do-you-normally-use-when-attempting-to-debug-a-problem-issue-bug-wi</a></p>

<p><a href="https://medium.com/javarevisited/debugging-deadlocks-and-race-conditions-8d184525a1fd#:~:text=This%20sounds%20complicated%2C%20but%20it,won%E2%80%99t%20see%20the%20problem%20occurring">[26]</a>
<a href="https://medium.com/javarevisited/debugging-deadlocks-and-race-conditions-8d184525a1fd#:~:text=debugging%20tools%20for%20a%20deadlock,won%E2%80%99t%20see%20the%20problem%20occurring">[27]</a>
<a href="https://medium.com/javarevisited/debugging-deadlocks-and-race-conditions-8d184525a1fd#:~:text=Again%2C%20we%20don%E2%80%99t%20suspend%20the,disturbed%20by%20the%20debugging%20process">[46]</a>
<a href="https://medium.com/javarevisited/debugging-deadlocks-and-race-conditions-8d184525a1fd#:~:text=TL%3BDR">[47]</a>
Debugging Deadlocks and Race Conditions | by Shai Almog |
Javarevisited | Medium</p>

<p><a href="https://medium.com/javarevisited/debugging-deadlocks-and-race-conditions-8d184525a1fd">https://medium.com/javarevisited/debugging-deadlocks-and-race-conditions-8d184525a1fd</a></p>

<p><a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=It%E2%80%99s%20common%20to%20see%20engineers,clue%20about%20the%20underlying%20cause">[30]</a>
<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=the%20mischievous%20bug%20in%20action,clue%20about%20the%20underlying%20cause">[31]</a>
<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=By%20manipulating%20input%20data%20and,that%20would%20otherwise%20remain%20undetected">[42]</a>
<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=,Blog">[43]</a>
<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=It%E2%80%99s%20common%20to%20see%20engineers,clue%20about%20the%20underlying%20cause">[45]</a>
<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=Randomized%20testing">[48]</a>
<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=A%20senior%20C%2B%2B%20developer%20consultant,told%20a%20colleague%20of%20mine">[49]</a>
<a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/#:~:text=They%20are%20difficult%20to%20catch,load%2C%20the%20bug%20may%20appear">[55]</a>
Debugging concurrency bugs in multithreaded applications - Time Travel
Debugging for C/C++ and Java ¦ Undo</p>

<p><a href="https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/">https://undo.io/resources/debugging-concurrency-bugs-multithreaded-applications/</a></p>

<p><a href="https://www.reddit.com/r/cpp/comments/1iqoaa7/professional_programmers_what_are_some_of_the/#:~:text=%E2%80%A2%20%201y%20ago">[39]</a>
Professional programmers: What are some of the most common debugging
errors for C++ (and C)? : r/cpp</p>

<p><a href="https://www.reddit.com/r/cpp/comments/1iqoaa7/professional_programmers_what_are_some_of_the/">https://www.reddit.com/r/cpp/comments/1iqoaa7/professional_programmers_what_are_some_of_the/</a></p>

<p><a href="https://stackoverflow.com/questions/1506131/how-to-debug-a-multithreaded-application-in-c-which-is-hung-deadlock#:~:text=The%20magic%20invocation%20in%20gdb,is">[44]</a>
multithreading - How to debug a multithreaded application in C++ which
is hung (deadlock)? - Stack Overflow</p>

<p><a href="https://stackoverflow.com/questions/1506131/how-to-debug-a-multithreaded-application-in-c-which-is-hung-deadlock">https://stackoverflow.com/questions/1506131/how-to-debug-a-multithreaded-application-in-c-which-is-hung-deadlock</a></p>]]></content><author><name>Colin Neilens</name></author><category term="cpp" /><category term="debugging" /><summary type="html"><![CDATA[Debugging is an essential skill for every software engineer. As Brian Kernighan famously noted, “Debugging is twice as hard as writing a program in the first place. So if you’re as clever as you can be when you write it, how will you ever debug it?”[1]. Studies suggest developers spend roughly 50% of their time debugging code[2]. This guide will help you develop a systematic, senior-level thought process for debugging tricky C++ issues – from single-threaded crashes to complex multi-threaded bugs – so you can tackle problems methodically and confidently.]]></summary></entry></feed>