在我的程序中,我使用全局变量alloc_ptr first_alloc = NULL;
,并使用结构和函数进行内存管理:
typedef struct alloc_struct
{
void* ptr;
struct alloc_struct* prev;
} *alloc_ptr;
void *alloc(unsigned long size)
{
alloc_ptr tmp = new struct alloc_struct;
tmp->ptr = new char[size];
tmp->prev = first_alloc;
first_alloc = tmp;
return tmp->ptr;
}
void free_one(void* ptr)
{
alloc_ptr tmp = first_alloc;
alloc_ptr tmp2 = tmp;
while(tmp != NULL)
{
if(ptr == tmp->ptr)
{
delete[] tmp->ptr;
if(tmp == first_alloc)
{
first_alloc = tmp->prev;
}
else
{
tmp2->prev = tmp->prev;
}
delete tmp;
break;
}
tmp2 = tmp;
tmp = tmp->prev;
}
}
void free_all()
{
alloc_ptr tmp;
while (first_alloc != NULL)
{
delete[] first_alloc->ptr;
tmp = first_alloc->prev;
delete first_alloc;
first_alloc = tmp;
}
first_alloc = NULL;
}
我使用valgrind尝试了我的程序,并在函数Mismatched free() / delete / delete []
和free_one
中收到了很多错误free_all
。如果我更改delete
和delete[]
则无效。这有什么问题?
感谢您的任何建议。
答案 0 :(得分:0)
尝试使用g ++ 6.3.0,编译器会生成以下内容 要求两行分配/释放ptr:
tmp->ptr = new char[size];
=> _Znam which is operator new[](unsigned long)/__builtin_vec_new
delete[] tmp->ptr;
=> _ZdlPv which is operator delete(void*)/__builtin_delete
所以,Valgrind抱怨似乎是正确的。
g ++还会发出警告,例如:
warning: deleting ‘void*’ is undefined [-Wdelete-incomplete]
delete[] tmp->ptr;
因此,您的代码是未定义的行为,编译器可以做任何事情,并且 已经决定生成触发valgrind错误的东西。