gcc
gcc -g -fsanitize=address <源码>
重载new运算符
void* MyMemoryTracker::allocate(size_t size) {
void* p = ::operator new(size);
std::cout << "__FUNCTION__" << endl;
return p;
}
void* operator new (size_t size , const char *file ,
unsigned int line ) {
if (void *ptr = malloc (size))
{
// print backtrace();
cout << endl << "new : " << file << " "<< line << endl ;
return ptr ;
}
throw std::bad_alloc () ;
}
Valgrind
valgrind会检测堆上的数组越界或内存泄露。
- 只能检查heap上的错误,不能检查出static和stack内存的使用,如数组越界等。
- 不能指出为什么泄漏,也不能指出在哪内存泄漏
- 指出的错误并非100%正确,但建议在编译时至少以warning的心态对待它们。
# 安装 valgrind
sudo apt install valgrind
# 使用valgrind检测内存泄露
valgrind --tool=memcheck --leak-check=full <可执行程序>