Spot a bug

I’ve found an interesting bug in a very old code today. Consider the following code snippet:

 1struct foo
 3    void* operator new(size_t t);
 4    void operator delete(void* p);
 5    int i;
 9    foo* f = new foo();
10    ::delete(f);
Can you spot a bug here? Read rest of the article for an answer. It all boils down to those two ‘:’ chars. It forces compiler to call global operator delete instead of this defined for class foo. If per-class operators use some kind of pool and dont fall back to malloc/free - it will result in a memory leak (in the best case).

Old comments

Liam 2010-11-25 16:41:31

Garett there are two sections to delete, the delete expression and the delete deallocation function which maybe overloaded. The delete expression will call the destructor if there is any present for the type and then will call the delete deallocation function.

admin 2010-11-23 02:54:23

Not in this case, you’d have to call operator delete(f) explicitly. delete(f) will still execute destructor (at least under MSVC).

Garett Bass 2010-11-22 19:05:16

It is trivial in this case, but calling global delete as a function also bypasses the destructor.

admin 2010-10-31 20:33:03

That is true, in 99% of cases it’s a mistake, however it’ll only pose a problem if there’s a per-class new operator, otherwise it doesn’t really matter.

Chris 2010-10-26 03:12:41

Even if it wasn’t overriding new and delete I still think it shouldn’t explicitly call the global version.