开发者

overloading operator new without overloading operator delete

开发者 https://www.devze.com 2023-01-22 22:39 出处:网络
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开发者_StackOverflow社区 I have a mismatch i.e. I

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开发者_StackOverflow社区 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)


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.


If you allocate with malloc you should free with free.

0

精彩评论

暂无评论...
验证码 换一张
取 消