简体   繁体   中英

overloading operator new without overloading operator delete

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 ie 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)

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

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.

如果使用malloc分配,则应使用free

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM