C++ 内存追踪器

main.c

复制代码
#include "pch.h"

struct Object
{
    int x,y,z;
};

int main()
{
    Print_MemoryUsage("strat");
    {
//        const char* string = "Cherno Cherno Cherno Cherno"; // 栈分配
        std::string string = "Cherno Cherno Cherno Cherno";  // >=15字节,堆分配
        Print_MemoryUsage("after string");
        {
            Object* obj = new Object();
//            std::unique_ptr<Object> obj = std::make_unique<Object>(); //自动 delete
            Print_MemoryUsage("after new");
            delete obj;
        }
        Print_MemoryUsage("after delete");
    }
    Print_MemoryUsage("end");
    

    std::cin.get();
}

pch.h

复制代码
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <fstream>
#include <sstream>
#include <thread>
#include <mutex>
#include <chrono>
#include <functional>
#include <algorithm>
#include <csignal>

// 内存追踪器
struct AllocationMetrics
{
    uint32_t TotalAllocated = 0;
    uint32_t TotalFreed = 0;

    uint32_t CurrentUsage()
    {
        return TotalAllocated - TotalFreed;
    }
};

static AllocationMetrics s_AllocationMetrics;

// 重载的内存分配函数
void *operator new(size_t size)
{
    s_AllocationMetrics.TotalAllocated += size;

    std::cout << "Allocating " << size << " bytes\n";
    return malloc(size);  // 实际分配
}

// 重载数组版的 new[]
void* operator new[](size_t size)
{
    s_AllocationMetrics.TotalAllocated += size;
    std::cout << "Allocating (array) " << size << " bytes\n";
    return malloc(size);
}

void operator delete(void* memory,size_t size)
{
    s_AllocationMetrics.TotalFreed += size;
    std::cout << "Freeing " << size << " bytes\n";
    free(memory);
}

// 重载数组版的 delete[] (带 size 参数)
void operator delete[](void* memory,size_t size) noexcept
{
    s_AllocationMetrics.TotalFreed += size;
    std::cout << "Freeing " << size << " bytes\n";
    free(memory);
}

// 无参数的后备版本
void operator delete(void* memory) noexcept
{
    free(memory);
}

// 重载数组版的 delete[] (无 size 参数,作为后备)
void operator delete[](void* memory) noexcept
{
    std::cout << "Freeing (unknown size)\n";
    // 这里依然无法追踪 size,但作为安全兜底
    free(memory);
}

// 工具函数
static void Print_MemoryUsage(const char* msg)
{
    std::cout << "Memory [" << msg << "]: " \
    << s_AllocationMetrics.CurrentUsage() << std::endl;
}
相关推荐
apcipot_rain16 小时前
C++转Java日记(03)
java·开发语言·c++
布莱克60516 小时前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
xys_67816 小时前
深挖C++:类和对象(中)
开发语言·c++
LongRunning18 小时前
【Linux】RK3568-OpenCV+YOLO(八)
linux·opencv·yolo
D e re k ZH19 小时前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法
xiaoye-duck20 小时前
《C++ 项目:手写大模型接入 SDK》Ollama接口设计(上):初始化、全量响应实现和测试
开发语言·网络·c++·语言模型
zaizai100720 小时前
【Effective Modern C++】学习第一章
c++
Fruiticecake21 小时前
C 程序员速通现代 C++(一):lambda、std::function、移动语义与智能指针
c语言·c++
民乐团扒谱机21 小时前
【微实验】NSGA-II(非支配排序遗传算法)——解决多目标优化问题的“自然选择模拟器”
linux·人工智能·算法
青少儿编程课堂21 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:中缀表达式求值解析
c++·python·算法·bfs·信息学竞赛