重载new/delete操作符并结合宏定义实现内存分配跟踪,通过记录分配信息检测泄漏与非法释放。

实现一个简单的内存分配跟踪器,能帮助开发者在调试阶段发现内存泄漏、重复释放和非法访问等问题。C++ 没有内置的内存跟踪机制,但我们可以重载全局的 new 和 delete 操作符,在其中插入日志记录逻辑,从而实现基础的跟踪功能。
通过重载全局的 new 和 delete,可以拦截所有使用这些操作符的内存申请与释放行为。
示例代码:
#include <iostream>
#include <map>
#include <cstdlib>
<p>// 用于记录分配信息
struct AllocInfo {
size_t size;
const char* file;
int line;
};</p><p>std::map<void*, AllocInfo> g_allocations;</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/6e7abc4abb9f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">C++免费学习笔记(深入)</a>”;</p><p>// 重载 new
void<em> operator new(size_t size, const char</em> file, int line) {
void* ptr = std::malloc(size);
if (ptr) {
g_allocations[ptr] = {size, file, line};
std::cout << "ALLOC: " << ptr << " size=" << size
<< " @ " << file << ":" << line << "\n";
}
return ptr;
}</p><p>// 提供普通 new 的重载(无文件行号)
void* operator new(size_t size) {
return ::operator new(size, "unknown", 0);
}</p><p>// 重载 delete
void operator delete(void* ptr) noexcept {
if (ptr == nullptr) return;</p><pre class='brush:php;toolbar:false;'>auto it = g_allocations.find(ptr);
if (it != g_allocations.end()) {
std::cout << "FREE: " << ptr << " size=" << it->second.size
<< " @ " << it->second.file << ":" << it->second.line << "\n";
g_allocations.erase(it);
} else {
std::cout << "FREE: " << ptr << " (UNKNOWN OR DOUBLE FREE!)\n";
}
std::free(ptr);}
直接写 new("file", line) 不现实,可以通过宏自动注入文件名和行号。
#define DEBUG_NEW new(__FILE__, __LINE__) // 使用时替换 new 为 DEBUG_NEW #define new DEBUG_NEW
这样写 new MyClass 实际上调用的是带位置信息的 new 版本。
程序结束前检查 g_allocations 是否为空,非空说明存在未释放的内存。
添加一个检测函数:
void check_leaks() {
if (g_allocations.empty()) {
std::cout << "No memory leaks detected.\n";
} else {
std::cout << "Memory leaks detected:\n";
for (const auto& pair : g_allocations) {
std::cout << "LEAK: " << pair.first
<< " size=" << pair.second.size
<< " @ " << pair.second.file
<< ":" << pair.second.line << "\n";
}
}
}
在 main 函数末尾调用 check_leaks() 即可看到结果。
这个简易跟踪器适合学习和小型项目,实际使用需注意:
基本上就这些。不复杂但容易忽略细节。只要把 new/delete 拦截好,加上位置信息和日志输出,就能构建出一个可用的内存跟踪工具。发布版本记得关闭宏定义避免影响性能。
以上就是c++++怎么实现一个简单的内存分配跟踪器_C++内存调试与跟踪工具实现的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号