Copying and deleting pointers with arrays

Copying one pointer to another element by element in C++ and getting "Error in `./hsc.exe': double free or corruption (!prev): 0x0000000000aadcc0 *** Aborted (core dumped)".

I tried to debug it and I get stuck at the line "delete[] rods;" as I can't delete rods as I am also deleting the information related to "temp".

Here is the following part of the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int * rods; // Defining rods and temp
int * temp;
int N_r =5;

rods = new int[N_r];
temp = new int[N_r];
for (int i = 0; i < N_r; i++){ // Copying rods to temp 
    temp[i] = rods[i];
}
delete[] rods; // deleting rods
rods = NULL;
rods = new int[N_r]; // creating new rods 
for (int i = 0; i < N_r; i++){ // copying temp to rods
    rods[i] = temp[i];
}
delete[] temp; // delete temp
temp = NULL;[code]
Last edited on
Hey and welcome =)

Please use code tags for all of your code - http://www.cplusplus.com/articles/jEywvCM9/

Kinda funny how you missed this actually, but take a look at this -
1
2
3
delete[] rods; // deleting rods
rods = NULL;
rods = new int[N_r]; // creating new rods  


Sure you delete rods, but as your comment says, you create a new rods, and then you never delete it again.

so you just need another delete[] rods; at the end of the program.
Last edited on
Hi TarikNeaj,

Thanks for code tags suggestion.

In debugger, I get problem at line 10 as this information is also being used by another pointer "temp". I can't delete[] rods at the end of it as I have to use rods[] for other purposes. Maybe I didn't understand what you said. :)

A couple of points:

You never initialise anything, it's just copying pointers.

This line:

temp[i] = rods[i];

assigns the same pointers literally, overwriting the ones in temp so the compiler complains about the double free, as you said.

If you had data, you could copy that, not the pointers :+) Do this by dereferencing the rods pointer.

Modern C++ shouldn't be using new and delete anyway, look into smart pointers - search std::unique_ptr

Hope this helps :+)
Yes. You are right. I should be focused about copying the data itself and not the pointers. Thanks.
Topic archived. No new replies allowed.