난 당신이 준 샘플 코드와 어떤 문제가 표시되지 않습니다.
다음 작품은 정상적으로 작동합니다.
[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)
NULL 포인터를 비우는 것은 완벽합니다.
free
함수는 공간, 즉 상기 할당에 이용 가능하게 ptr
가 해제 될 가리키는시킨다. ptr
이 널 포인터 인 경우, 조치가 발생하지 않습니다..
그래서 if (ptr == NULL) return;
은 생략 할 수 있습니다.
두 번 개체를 삭제 또는'new'를 호출 얻을 수없는 포인터를 통해 개체를 삭제하려고합니까? –
부수적으로,'free (NULL)'은 안전하다는 것을 보장한다. (아무 것도하지 않는다.) 그래서 특별한 경우는 필요 없다. –
hm ... 나쁘다 : 만약'if (size == 0)'을'if (size = 0)'로 바꾸고 생성자뿐만 아니라 private 데이터 멤버를 추가하면 코드는 실패 할 것이다. 나는'size = 0'은 발생해서는 안되지만 생성자에서이 클래스의 private 데이터 멤버를 초기화 할 때만 코드가 실패하는 버그라는 것을 알고 있습니다. – Jaywalker