c++ - 重载 operator new 而不重载 operator delete

标签 c++ memory-leaks

大家好

我有下面的简单代码。我为我的类(class)定义了 operator new 而没有 operator delete。 根据 valgrind --leak-check=yes PROGRAM_NAME 我有一个不匹配,即我正在使用 new[] 为数组分配,但我正在使用简单的 delete 解除分配 对于非数组。你知道为什么吗?

问候 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)

最佳答案

您的重载运算符 new 使用 malloc,但随后您使用普通的 C++ delete 运算符解除分配。这是一个典型的错误。如果您使用 malloc 分配,则必须始终使用free 释放。如果您使用 new 进行分配,则必须始终使用 delete 解除分配(对于数组,则为 delete[] ).

您需要重载 delete 运算符并让它调用 free()

关于c++ - 重载 operator new 而不重载 operator delete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4059012/

相关文章:

c++ - 通过 qDebug 打印 qByteArray

node.js - 在生产中查找 nodejs 中的内存泄漏

C++ 堆栈使用模板化链表 - 内存泄漏

c++ - 隐式转换和函数运算符

c++ - 按不同字段对结构队列进行排序

c++ - __STDCPP_DEFAULT_NEW_ALIGNMENT__ 出现之前的年龄是多少

java - 实现 canvas.drawBitmap 方法时如何避免内存泄漏?

c++ - 在 C++ 中删除命名空间 boost

快速组合接收器接收值内存泄漏

memory - 转储 Valgrind 报告的丢失内存的内容