我看不出有什麼問題,你給的示例代碼。
以下工作適合我。
[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