0

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.

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;
  • Are you using any programming language in particular? – Daniel Daranas Feb 12 '16 at 09:03
  • 1
    You should have generated a simple example which can be compiled independently and reproduces the problem. That said, the way you play with native arrays, raw pointers, new, copy and delete is almost bound to lead to trouble. It is simply not safe. – Daniel Daranas Feb 12 '16 at 09:19
  • 1
    temp[i]= rods[i]; there's a possibility of shallow copy , so there might be a chance you are freeing the memory twice – evk1206 Feb 12 '16 at 09:26
  • This code is correct. Whats the compiler? – Alexander Chernin Feb 12 '16 at 09:38
  • You should get this error if you try delete an array twice. int[] a = new int[N]; delete[] a; delete[] a; But in the snippet you just make data copy from one place of the memory to another. Its correct http://www.cplusplus.com/forum/general/22527/ – Alexander Chernin Feb 12 '16 at 09:42
  • Yes. 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". I am looking for a smarter way to avoid this problem. – Mohit Dixit Feb 12 '16 at 09:46
  • 1
    May be this help? http://stackoverflow.com/questions/14063791/double-free-or-corruption-but-why – Alexander Chernin Feb 12 '16 at 09:49

1 Answers1

0

double free or corruption Error:

There is a possibilty that this is due to shallow copy. You should use overloaded = operator.

rods[i]= temp[i];

might lead to this and both the objects have the data members pointing to the same location and when you call delete from both , you are freeing the memory allocated twice. See about COpy constructor and overloading = operator.

evk1206
  • 433
  • 7
  • 18