Re: NULL pointer in overloaded operator delete []
On Nov 13, 8:13 pm, Andrey Tarasevich <andreytarasev...@hotmail.com>
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?
*/
}
Unfortunately, the language specification is (was?) not sufficiently
clear on whether the control should go into the overloaded 'operator
delete' when the delete-expression is invoked on the null-pointer of
corresponding type, even though the standard does say that
delete-expression on null-pointer is a no-op. Apparently Sun compiler
thinks that it should be called.
Meanwhile, I don't understand why it crashes on Sun, even if it gets
into the above 'operator delete[]'. The standard 'free' function is also
a no-op on a null-pointer argument. If it crashes, that would mean that
there's a bug in Sun's 'free' implementation.
BTW, how do you know that VC and g++ don't call it? You really checked
it or you just assumed it because it didn't crash?
--
Best regards,
Andrey Tarasevich- Hide quoted text -
- Show quoted text -
Hi,
Sorry for my ignorance. But that is just a dummy code which I wrote
quickly, so actually its "int main" only
and the operator delete [] does not call free(), It manages a double
linked list internally and de-references the pointer p before actually
freeing the memory. Which causes a crash.
So I wanted to know if I should put a platform specific NULL check in
operator delete [] OR should make it general. Doing that would
penalize other platforms un-necessarily, of-course the cost is not
much considering the whole application. But my point is, why to
penalize other platforms if they are behaving as per the standard (If
at all they are ).=94