简体   繁体   中英

“free(): double free detected in tcache 2” in dynamic array class in C++

I want to write a dynamic array class in C++. I get this message: free(): double free detected in tcache 2 when I run the code.

This is part of my code:

        if(num_of_items >= size)
        {
            int new_size = size < 5 ? 2 * size : (int)(3/2 * size);
            int * temp = new int[new_size];
            
            for(int i = 0; i<size; i++)
            {
                temp[i] = items[i];
            }

            delete [] items;
            items = temp;
            delete [] temp; // This is the line that the program shows the message

            size = new_size;
        }

num_of_items is number of full blocks of array. I use a debugger to find the problems place, I find delete [] temp; line as problem's line. Why I get this message?

Your pointer temp is the new, larger array, which your object needs to hold. You delete it, leaving your object in a bad state.

The remedy is easy, delete this line: delete [] temp;

It looks like you do this in your loop:

 delete [] items;
 items = temp;
 delete [] temp;

And then repeat. So the second time through the loop, items points to data you already deleted. I think you need to get rid of the second delete[].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM