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;
}
相关推荐
程序员梅雨6 小时前
Linux & Shell 实用干货
linux·运维·服务器·后端·面试·php
吴声子夜歌6 小时前
编写Shell脚本——自顶向下设计
linux·运维·shell
小七在进步6 小时前
C++入门(2)
java·jvm·c++
M78佐菲6 小时前
HTML学习笔记
linux·笔记·学习·tcp/ip·html
新时代牛马6 小时前
嵌入式 Linux 蓝牙框架完整篇:从 HCI、L2CAP 到BlueZ 用户态
linux·运维·服务器
en.en..7 小时前
C语言核心解析:#define与typedef本质区别
开发语言·c++·算法
Brilliantwxx7 小时前
【STM32】 初认识USART串口
linux·stm32·单片机·嵌入式硬件·架构
码匠许师傅7 小时前
【设计模式精讲】26.策略模式(Strategy)
c++·设计模式·策略模式·uml
aningx7 小时前
使用自定义bash脚本预防oom卡死
linux
ONLYOFFICE7 小时前
ONLYOFFICE成为Linux操作系统 – Winux的预装办公套件
linux·运维·服务器