You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Linux/macOS平台检测内存泄漏?自定义堆监控头文件适配

Detecting Memory Leaks on Linux/macOS

Great question! Since you’re already comfortable with Windows’ CRT-based heap monitoring via your heap_monitor.h, let’s walk through the most reliable and commonly used methods for Linux and macOS.

1. Valgrind (The Classic Go-To Tool)

Valgrind is a tried-and-true instrumentation framework that includes memcheck—a tool built specifically to catch memory leaks, invalid memory accesses, and other heap-related bugs. It works seamlessly on Linux, and has partial support for older macOS versions (note: newer macOS releases may have limited compatibility due to system-level changes).

How to use it:

  • First, install Valgrind:
    • On Linux: sudo apt install valgrind (Debian/Ubuntu) or sudo dnf install valgrind (Fedora/RHEL)
    • On macOS: brew install valgrind (via Homebrew, though support for recent macOS versions is spotty)
  • Compile your program with debug symbols so Valgrind can map leaks to specific code lines:
    g++ -g your_program.cpp -o your_program
    
  • Run your program under Valgrind’s memcheck tool:
    valgrind --leak-check=full ./your_program
    

What to look for:

After your program exits, Valgrind will output a detailed report. Focus on these key sections:

  • Definitely lost: These are memory blocks your program allocated but never freed, with no remaining pointers to them—this is exactly the type of leak your Windows CRT setup catches.
  • Thanks to the -g compile flag, the report will show the exact file and line number where the leaked memory was allocated, just like your heap_monitor.h does.

2. AddressSanitizer (ASAN) – Fast & Modern Alternative

AddressSanitizer (developed by Google) is integrated directly into GCC and Clang. It’s way faster than Valgrind (runs at ~2x slowdown vs Valgrind’s 10-50x) and produces clear, actionable leak reports. It’s fully supported on both Linux and macOS.

How to use it:

  • Compile your program with ASAN enabled plus debug symbols:
    g++ -g -fsanitize=address your_program.cpp -o your_program
    
  • Run your program normally—no extra wrappers needed:
    ./your_program
    

What to expect:

When your program exits, ASAN will automatically print a memory leak report if any issues are found. The report includes:

  • The full call stack of where the leaked memory was allocated (with file and line numbers)
  • The size of each leaked block
  • A summary of total leaked memory

You can tweak behavior with environment variables like ASAN_OPTIONS=detect_leaks=1 (though leak detection is enabled by default in most versions).

3. Custom Code-Level Tracking (Similar to Your Windows Header)

If you want a setup that mirrors your heap_monitor.h (enabling tracking via header inclusion), you can overload C++’s operator new and operator delete to track allocations manually. This is less robust than dedicated tools, but here’s a quick example:

Create a header like linux_heap_monitor.h:

#pragma once
#include <iostream>
#include <unordered_map>
#include <cstdlib>

// Track allocations with file/line metadata
static std::unordered_map<void*, std::pair<const char*, int>> allocations;

void* operator new(size_t size, const char* file, int line) {
    void* ptr = malloc(size);
    allocations[ptr] = {file, line};
    return ptr;
}

void operator delete(void* ptr) noexcept {
    allocations.erase(ptr);
    free(ptr);
}

// Redefine new to pass file/line info automatically
#define new new (__FILE__, __LINE__)

// Check for leaks when the program exits
static void checkLeaks() {
    if (!allocations.empty()) {
        std::cerr << "Memory leaks detected:\n";
        for (const auto& [ptr, loc] : allocations) {
            std::cerr << "Leaked " << malloc_usable_size(ptr) << " bytes at " << loc.first << ":" << loc.second << "\n";
        }
    }
}

// Register leak check to run on program exit
static struct LeakChecker {
    ~LeakChecker() { checkLeaks(); }
} leakChecker;

Include this header in your files just like your Windows version. Keep in mind: this won’t catch leaks from raw C-style malloc/free unless you wrap those too, and it’s less thorough than Valgrind or ASAN.

Quick Recommendations

  • For most projects, AddressSanitizer is the best choice—it’s fast, easy to integrate into your build process, and catches more than just leaks.
  • Valgrind is still useful for catching subtle memory bugs (like use-after-free) on systems where ASAN isn’t available.
  • Unlike your Windows CRT setup, you don’t need to modify your core code to use these tools—just add a few compile flags.

内容的提问来源于stack exchange,提问作者Hajdučák Marek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:35:45