大家好
我有下面的简单代码.我为我的类定义了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;
Run Code Online (Sandbox Code Playgroud)
}
==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().
| 归档时间: |
|
| 查看次数: |
569 次 |
| 最近记录: |