Re: NULL pointer in overloaded operator delete []
On Nov 13, 2:50 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
Rahul wrote:
Please read the following code
class Test{
public:
void * operator new [] (size_t t)
{ return malloc(t); }
void operator delete [] (void *p)
{ free(p); }
};
void main () {
Test *p= 0;
delete [] p;
/* What should happen here, Should the call go inside Test::operator
delete []. Because what I learned from books is that deleting a NULL
pointer is safe (calling ::operator delete[] on a NULL pointer does
not crash). But here it causes a crash on Sun CC because it gets
inside Test::operator delete [] whereas on VC++ and g++ it doesn't.
Should I put a check in Test::operator delete [] for "p=
!
=NULL"? Is Sun CC behaving as per the C++ standard?
The behaviour of your program is undefined. 'main' must
return the type 'int':
Not undefined. It's an error which requires a diagnosis.
Of course, that is completely orthogonal to his question.
int main() {
Seriously, though, everything should be OK because 'free' is
explicitly specified as a NOP if its argument is a null
pointer.
You need to investigate further why on Sun it doesn't go into
the overloaded operator delete[]. And even if you don't
overload, the deletion (using 'delete' or 'delete[]') is
explicitly defined as OK if the argument is a null pointer.
It's still the responisiblity of operator delete (or delete[])
to check; the standard doesn't guarantee that it won't be given
a null pointer; the standard requires that it be a no-op if
given a null pointer.
But of course, all he's doing is calling free() with the pointer,
and free() is guaranteed to be a no-op when given a null
pointer, so his implementation meets the requirements.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34