0
votes

HI All

I have the simple code below. I defined operator new for my class without operator delete. According to valgrind --leak-check=yes PROGRAM_NAME I have a mismatch i.e. I am allocating using new[] for arrays, but I am deallocating with simple delete for non array. Do you know why?

Regards AFG

#include<string>
#include<new>


class CA{
public:
CA(){
    std::cout << "*created CA*";
}   

~CA(){
    std::cout << "*deleted*";
}

void* operator new( std::size_t aSize ){
    std::cout << "*MY NEW*";
    void* storage = std::malloc( aSize );
    if( !storage )
    {
        std::exception ex;
        throw ex;
    }
    return storage;
}};

int main(int argc, char** argv){
CA* p = new CA();
delete p;   
return 0;

}

==2767== Mismatched free() / delete / delete []
==2767==    at 0x4024851: operator delete(void*) (vg_replace_malloc.c:387)
==2767==    by 0x80488BD: main (operator_new_test.cpp:54)
==2767==  Address 0x42d3028 is 0 bytes inside a block of size 1 alloc'd
==2767==    at 0x4024F20: malloc (vg_replace_malloc.c:236)
==2767==    by 0x80489A4: CA::operator new(unsigned int) (operator_new_test.cpp:18)
==2767==    by 0x804887B: main (operator_new_test.cpp:53)
3
Unrelated to the question, but new should throw std::bad_alloc on failure. - Steve Jessop
@Steve: If only someone had answered with a foolproof way to overload global new. :) - Roger Pate

3 Answers

8
votes

Your overloaded operator new uses malloc, but then you deallocate using the normal C++ delete operator. This is a classic error. If you allocate with malloc, you must always deallocate with free. If you allocate with new, you must always deallocate with delete (or delete[] in the case of arrays).

You'll need to overload the delete operator and have it call free().

1
votes

When you overload operator new, you must overload operator delete so you know the right deallocation function (free, in this case) is called.

There's a couple of problems with your overload as well; see my example on overloading new. Simply replace allocate_from_some_other_source with malloc and deallocate_from_some_other_source with free.

0
votes

If you allocate with malloc you should free with free.