我看不出有什么问题,你给的示例代码。
以下工作适合我。
[email protected] ~ $ cat leak_check.cpp && g++ leak_check.cpp && valgrind --leak-check=full ./a.out
#include <cstdlib>
class Base {
public:
static void * operator new (size_t size) {
if (size == 0) size = 1;
return malloc (size);
}
static void operator delete (void *ptr, size_t size) {
if (ptr == NULL) return;
free (ptr);
}
};
int main()
{
Base * p = (Base *) Base::operator new(sizeof(Base));
Base::operator delete((void*)p,sizeof(Base));
}
==4561== Memcheck, a memory error detector
==4561== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==4561== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==4561== Command: ./a.out
==4561==
==4561==
==4561== HEAP SUMMARY:
==4561== in use at exit: 0 bytes in 0 blocks
==4561== total heap usage: 1 allocs, 1 frees, 1 bytes allocated
==4561==
==4561== All heap blocks were freed -- no leaks are possible
==4561==
==4561== For counts of detected and suppressed errors, rerun with: -v
==4561== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 17 from 6)
顺便说一句,释放空指针是非常好的。
的free
功能使空间指向ptr
被解除分配,即,提供用于进一步的分配。如果ptr
是空指针,则不会发生动作。
因此if (ptr == NULL) return;
可以省略。
你们是不是要删除对象两次或删除通过指针不调用`new`获得的对象? – 2010-11-27 06:57:43
作为一个方面说明,`free(NULL)`保证是安全的(一个无操作),所以你不必特殊情况。 – 2010-11-27 07:14:57