Spook
Spook

Reputation: 373

C++ - valgrind - Mismatched free() / delete / delete []

In my program I use global variable alloc_ptr first_alloc = NULL; and following struct and functions for memory management:

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;
}

I tried my program with valgrind and received lots of errors Mismatched free() / delete / delete [] in functions free_one and free_all. If I change delete and delete[] it has no effect. What is the problem here?

Thanks for any advice.

Upvotes: 0

Views: 10228

Answers (1)

phd
phd

Reputation: 3807

Trying with g++ 6.3.0, the compiler generates the following calls for the two lines allocating/freeing 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

So, Valgrind complains seems correct.

g++ also gives warnings such as :

warning: deleting ‘void*’ is undefined [-Wdelete-incomplete]
             delete[] tmp->ptr;

So, your code is undefined behaviour, the compiler can do whatever, and has decided to generate something that triggers a valgrind error.

Upvotes: 3

Related Questions