Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator delete causing heap corruption while operator new working fine

I have got operator new working but as soon as I call delete, it crashes at the free (ptr) line. Can any one tell what I am doing wrong when overloading operator new and delete in this Base class? Hint: I am not asking about design issues.

class Base {
private: 
    int i;

public:  
    Base () : i (10) {
    }

    static void * operator new (size_t size) {  
       if (size = 0) size = 1;  // please read this line carefully! size = 0!
       return malloc (size);  
    }

    static void operator delete (void *ptr, size_t size) {
       if (ptr == NULL) return;
       free (ptr);
    }
};
like image 901
Jaywalker Avatar asked Nov 27 '10 06:11

Jaywalker


People also ask

Can delete operator be overloaded?

New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.

What does the operator delete do?

Using the delete operator on an object deallocates its memory. A program that dereferences a pointer after the object is deleted can have unpredictable results or crash.

Which operator is used to destroy memory?

Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. New operator is used for dynamic memory allocation which puts variables on heap memory. Which means Delete operator deallocates memory from heap.

Does operator delete call destructor?

The answer is yes. Destructor for each object is called. On a related note, you should try to avoid using delete whenever possible.


1 Answers

This works for me:

#include <cstdlib>
using namespace std;
class Base {
public:
    void * operator new(size_t size) {
       if (size == 0) size = 1;
       return malloc (size);
    }

    void operator delete (void *ptr, size_t size) {
       if (ptr == NULL) return;
       free (ptr);
    }
};

int main()
{
    Base* b = new Base;
    delete b;
    return 0;
}

hank@tardis:/tmp$ g++ -o test test.cpp 
hank@tardis:/tmp$ ./test 
hank@tardis:/tmp$ valgrind ./test 
==7229== HEAP SUMMARY:
==7229==     in use at exit: 0 bytes in 0 blocks
==7229==   total heap usage: 1 allocs, 1 frees, 1 bytes allocated
==7229== 
==7229== All heap blocks were freed -- no leaks are possible
==7229== 
==7229== For counts of detected and suppressed errors, rerun with: -v
==7229== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
like image 113
Hank Avatar answered Nov 02 '22 21:11

Hank