【问题标题】:Copying and deleting pointers with arrays使用数组复制和删除指针
【发布时间】:2016-02-12 09:01:40
【问题描述】:

在 C++ 中逐个元素地复制一个指向另一个元素的指针并得到“`./hsc.exe' 中的错误:双重释放或损坏(!prev):0x0000000000aadcc0 *** 中止(核心转储)”。

我尝试调试它,但卡在“delete[] rods;”这一行。因为我不能删除棒,因为我也在删除与“temp”相关的信息。

下面是代码部分。

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;

【问题讨论】:

  • 您是否特别使用任何编程语言?
  • 您应该已经生成了一个可以独立编译并重现问题的简单示例。也就是说,您使用本机数组、原始指针、新建、复制和删除的方式几乎必然会导致麻烦。这根本不安全。
  • temp[i]= rods[i];存在浅拷贝的可能性,因此您可能会释放两次内存
  • 这段代码是正确的。编译器是什么?
  • 这可能有帮助吗? stackoverflow.com/questions/14063791/…

标签: c++ pointers copying


【解决方案1】:

双重释放或损坏错误:

这有可能是由于浅拷贝造成的。您应该使用重载 = 运算符。

rods[i]= temp[i];

可能会导致这种情况,并且两个对象的数据成员都指向相同的位置,当您从两者调用 delete 时,您将释放两次分配的内存。请参阅 COpy 构造函数和重载 = 运算符。

【讨论】:

    猜你喜欢
    • 2014-04-19
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多