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;
}
