惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threatpost
AI
AI
T
Threat Research - Cisco Blogs
Know Your Adversary
Know Your Adversary
C
CERT Recently Published Vulnerability Notes
V
Vulnerabilities – Threatpost
S
Securelist
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Tenable Blog
C
Cybersecurity and Infrastructure Security Agency CISA
AWS News Blog
AWS News Blog
Cisco Talos Blog
Cisco Talos Blog
Cloudbric
Cloudbric
P
Privacy & Cybersecurity Law Blog
N
News and Events Feed by Topic
D
Docker
博客园 - 司徒正美
Last Week in AI
Last Week in AI
Google DeepMind News
Google DeepMind News
O
OpenAI News
人人都是产品经理
人人都是产品经理
腾讯CDC
博客园 - 三生石上(FineUI控件)
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Scott Helme
Scott Helme
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The GitHub Blog
The GitHub Blog
Microsoft Security Blog
Microsoft Security Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
博客园 - 叶小钗
N
News and Events Feed by Topic
J
Java Code Geeks
D
DataBreaches.Net
爱范儿
爱范儿
N
Netflix TechBlog - Medium
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
H
Heimdal Security Blog
F
Full Disclosure
L
LINUX DO - 最新话题
W
WeLiveSecurity
Blog — PlanetScale
Blog — PlanetScale
V
V2EX
M
MIT News - Artificial intelligence
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - Franky
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
U
Unit 42

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Finding Memory Leaks in Legacy C++ Applications with Valgrind
Wang - C++ D · 2026-05-07 · via DEV Community

Legacy C++ services don't crash — they slowly bleed memory until someone restarts them at 3 AM.

If you've inherited a 20‑year‑old codebase with mysterious memory growth, this guide is for you.

You can't fix a leak if you can't reproduce.

This is your complete, production‑focused Valgrind investigation playbook.
It's based on real systems, real leaks, and real debugging pain.


Table of Contents


The Workflow

[Leak Trigger] → [Static Analysis] → [Compile Debug Build]
        ↓
   [Run Valgrind] → [Interpret Leak Types] → [Stack Trace]
        ↓
     [Regression Test]

Enter fullscreen mode Exit fullscreen mode


Step 1 — Reproduce the Leak

You cannot find a leak if you cannot trigger it.

Measure memory growth

use the following script to track the total memory of your application used.

PID=$(pgrep your_service)
while true; do
  echo "$(date): $(pmap $PID | grep total | awk '{print $2}')"
  sleep 60
done

Enter fullscreen mode Exit fullscreen mode

Interpretation:

Pattern Meaning
Linear growth Per‑operation leak
Step‑function growth Specific trigger
No growth Wrong hypothesis

Find the minimum trigger

Your goal: reproduce the leak in under 10 minutes.

Why?

  • Valgrind slows execution by 20–50×
  • A 10‑minute trigger becomes 3–8 hours
  • A 1‑hour trigger becomes 2–5 days

Why this matters: If your trigger is too slow, Valgrind becomes unusable.


Step 2 — Static Analysis (5 minutes, zero runtime cost)

Before running anything, let the compiler find the obvious issues.

Clang Static Analyzer

scan-build make

Enter fullscreen mode Exit fullscreen mode

Look for "Memory leak" warnings (ignore "Potential leak").

clang‑tidy

clang-tidy legacy_file.cpp \
  --checks='-*,clang-analyzer-*,cppcoreguidelines-owning-memory'

Enter fullscreen mode Exit fullscreen mode

Finds:

  • new without delete
  • malloc without free
  • Raw owning pointers

Misses:

  • Cycles
  • Third‑party leaks
  • Runtime‑dependent leaks

Why this matters: Static analysis gives you free wins before you even run the program.


Step 3 — Compile for Valgrind

Valgrind is useless without debug symbols. So first thing you should do is to compile the whole application with debug flag.

g++ -g3 -O0 -fno-omit-frame-pointer -o your_service your_service.cpp

Enter fullscreen mode Exit fullscreen mode

Flag Purpose
-g3 Full debug info
-O0 Clean stack frames
-fno-omit-frame-pointer Reliable backtraces

Why this matters: Without debug symbols, Valgrind can't show you file/line numbers.


Step 4 — Run Valgrind

Run only the trigger you identified in Step 1.

valgrind --leak-check=full \
         --show-leak-kinds=definite,indirect \
         --track-origins=yes \
         --log-file=valgrind_out.txt \
         ./your_service --run-trigger

Enter fullscreen mode Exit fullscreen mode

For long‑running services

Use vgdb to inspect leaks mid‑run:

valgrind --vgdb=yes --vgdb-error=0 --leak-check=full ./your_service

Enter fullscreen mode Exit fullscreen mode

Then:

vgdb leak_check full definite indirect

Enter fullscreen mode Exit fullscreen mode

Why this matters: You don't need to wait hours — you can inspect leaks while running.


Step 5 — Understand Valgrind's Leak Types

After the run, Valgrind will give you a report about memory lost in valgrind_out.txt. Example summary:

definitely lost: 1,024 bytes
indirectly lost: 6,144 bytes
possibly lost: 0 bytes
still reachable: 45,000 bytes

Enter fullscreen mode Exit fullscreen mode

What each type means

Valgrind gives the following types of memory lost. Based on the types, you decides your action.

Type Meaning Action
definitely lost Real leak Fix first
indirectly lost Child of a lost block Fix parent
possibly lost Pointer arithmetic / corruption Investigate
still reachable Globals/statics Ignore unless growing

If "still reachable" grows

Use Massif:

valgrind --tool=massif ./your_trigger
ms_print massif.out

Enter fullscreen mode Exit fullscreen mode

Why this matters: "Still reachable" is not a leak — unless it grows.


Step 6 — Capture the Stack Trace

A real leak looks like the following. With the stack trace and debug symbols, exact source file name and line number will be given. That is where memory is allocated. To fix it, you need to find out why the allocated memory was not released, e.g. delete is only called on one running path. With the trigger, another running path is active.

1,024 bytes in 1 blocks are definitely lost
at operator new
by DatabaseConnection::ExecuteQuery (db_connection.cpp:67)
by CustomerLoader::FetchCustomer (customer_loader.cpp:89)

Enter fullscreen mode Exit fullscreen mode

Extract only leak blocks:

grep -A10 "definitely lost" valgrind_out.txt

Enter fullscreen mode Exit fullscreen mode

Why this matters: The stack trace is the map that leads you to the leak.


Step 7 — Optional Regression Test

Useful when multiple developers touch the code.

TEST(LeakTest, ConfirmLeakExists) {
    size_t before = get_current_rss();
    for (int i = 0; i < 100; i++) {
        suspect_function();
    }
    size_t after = get_current_rss();
    EXPECT_LT((after - before) / 100, 1024);
}

Enter fullscreen mode Exit fullscreen mode

Why this matters: Regression tests prevent old leaks from returning.


Quick Reference

Task Command
Basic leak check valgrind --leak-check=full ./binary
Only real leaks --show-leak-kinds=definite,indirect
Save output --log-file=leak.log
Check running service vgdb leak_check full definite indirect
Heap profiling valgrind --tool=massif
Extract leak grep -A10 "definitely lost"

Real‑World Example

Imagine a legacy service that loads customers from a database and caches them.

The bug

// customer_loader.h
struct Customer {
    int id;
    std::string name;
};

class CustomerRepository {
public:
    Customer* LoadCustomer(int id);
};

Enter fullscreen mode Exit fullscreen mode

// customer_loader.cpp
#include "customer_loader.h"
#include "db_connection.h"

Customer* CustomerRepository::LoadCustomer(int id)
{
    DatabaseConnection* conn = DatabaseConnection::Get(); // singleton
    ResultSet* rs = conn->ExecuteQuery("SELECT id, name FROM customers WHERE id = " + std::to_string(id));

    if (!rs->Next()) {
        return nullptr;
    }

    Customer* c = new Customer{};
    c->id = rs->GetInt(0);
    c->name = rs->GetString(1);

    // BUG: ResultSet is never deleted
    // delete rs;  // missing

    return c; // caller owns Customer*
}

Enter fullscreen mode Exit fullscreen mode

Caller code:

void ProcessRequest(int customerId)
{
    CustomerRepository repo;
    Customer* c = repo.LoadCustomer(customerId);

    if (!c) {
        return;
    }

    // ... use c ...

    delete c; // correct
}

Enter fullscreen mode Exit fullscreen mode

At first glance, this looks “fine” because Customer is deleted.

But ResultSet is leaked on every call.


Valgrind report

You run your request handler under Valgrind:

valgrind --leak-check=full \
         --show-leak-kinds=definite,indirect \
         --track-origins=yes \
         --log-file=valgrind_leak.log \
         ./service --handle-request 42

Enter fullscreen mode Exit fullscreen mode

Relevant part of the report:

==12345== 128 bytes in 1 blocks are definitely lost in loss record 3 of 5
==12345==    at 0x4C2F1A3: operator new(unsigned long) (vg_replace_malloc.c:422)
==12345==    by 0x401F8B: ResultSet::ResultSet(DBHandle*) (result_set.cpp:27)
==12345==    by 0x4023D1: DatabaseConnection::ExecuteQuery(std::string const&) (db_connection.cpp:88)
==12345==    by 0x4039A4: CustomerRepository::LoadCustomer(int) (customer_loader.cpp:11)
==12345==    by 0x40412F: ProcessRequest(int) (request_handler.cpp:25)
==12345==    by 0x4043C9: main (main.cpp:17)

Enter fullscreen mode Exit fullscreen mode

Key points:

  • “128 bytes in 1 blocks are definitely lost” → real leak
  • Allocation happens in ResultSet::ResultSet
  • The call chain leads to CustomerRepository::LoadCustomer

You don’t need to know ResultSet internals—only that you allocated it and never freed it.


The fix

Customer* CustomerRepository::LoadCustomer(int id)
{
    DatabaseConnection* conn = DatabaseConnection::Get();
    ResultSet* rs = conn->ExecuteQuery("SELECT id, name FROM customers WHERE id = " + std::to_string(id));

    if (!rs->Next()) {
        delete rs;          // ✅ free on early return
        return nullptr;
    }

    Customer* c = new Customer{};
    c->id = rs->GetInt(0);
    c->name = rs->GetString(1);

    delete rs;              // ✅ free after use

    return c;
}

Enter fullscreen mode Exit fullscreen mode

Re‑run Valgrind:

==12345== HEAP SUMMARY:
==12345==     in use at exit: 0 bytes in 0 blocks
==12345==   total heap usage: 1,234 allocs, 1,234 frees, 98,765 bytes allocated
==12345== 
==12345== All heap blocks were freed -- no leaks are possible

Enter fullscreen mode Exit fullscreen mode


The Golden Rule

Never start fixing until you can reproduce the leak in under 10 minutes.

The trigger is your truth.
The stack trace is your map.