views:

41

answers:

3

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)
A: 

If you allocate with malloc you should free with free.

Amnon
+7  A: 

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().

Charles Salvia
+1 -- do you ever get the feeling that we'll all be explaining this until we're very very old?
bgporter
One day I'll give some important advice about life to my grandchildren: never mix `malloc` and `new`, or you'll end up regretting it some day.
Charles Salvia
I usually use the pair new/delete and new[]/delete[]. I though that since malloc is used in new this one would have been masked someway, so in my head looked like a common pair new/delete. Thanks a lot for the kind response!
Abruzzo Forte e Gentile
+1  A: 

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.

Roger Pate