简体   繁体   English

将一个数组分配给堆上的另一个数组 C++

[英]Assigning an Array to Another Array on the Heap C++

T is = to char T是 = 到字符
counts_ is an array of integers stored on the heap counts_是存储在堆上的整数数组
values_ is an array of arrays on the heap values_是堆上的数组数组

Problem arrives in the if statement, when I try to delete tmpe I get an error.问题出现在 if 语句中,当我尝试删除tmpe出现错误。 If I comment the delete statement out, the code runs but it just keeps pointing all of my pointers in values_ to the same array.如果我注释掉 delete 语句,代码会运行,但它只是将values_中的所有指针都指向同一个数组。 The idea of the code is to create a new array containing the values of one of the selected values_ arrays and then add one extra value to it.代码的想法是创建一个包含所选values_数组之一的值的新数组,然后向其中添加一个额外的值。 Then re-assign it back to the spot in the values_ array that I took it from.然后将它重新分配回我values_数组中的位置。 The tmpe array is holding the correct values up to the point that I attempt to delete the pointer to it. tmpe数组一直保存正确的值,直到我尝试删除指向它的指针为止。 I get a Aborted (core dumped) error upon running my entire program.运行我的整个程序时出现中止(核心转储)错误。

if (initialized(n) == true)
{   
    T *tmpe = new T[counts_[n] + 1];
    for (size_type i = 0; i < counts_[n]; i++)
    {
        tmpe[i] = values_[n][i];
    }
    tmpe[counts_[n]] = val;
    delete [] values_[n];
    values_[n] = tmpe;
    delete [] tmpe;
    counts_[n]++;
}
else
{
    T *tmpd = new T[counts_[n] + 1];
    tmpd[counts_[n]] = val;
    delete [] values_[n];
    values_[n] = tmpd;
    delete [] tmpd;
    counts_[n]++;
}

The issue is that you keep a pointer to tmpe but promptly deallocate the memory:问题是你保留了一个指向tmpe的指针,但迅速释放了内存:

values_[n] = tmpe;
delete [] tmpe;

When the next iteration tries to access and/or delete values_[n] , it's a dangling pointer.当下一次迭代尝试访问和/或删除values_[n] ,它是一个悬空指针。

The same goes for tmpd . tmpd

If you used std::vector , you wouldn't have to worry about problems like this.如果你使用std::vector ,你就不必担心这样的问题。

You don't need to delete tmpd after you reassign values_ to point to it.重新分配values_以指向它后,您无需删除tmpd As soon as you reassign it, the memory is freed.一旦你重新分配它,内存就会被释放。 What's happening is that you're trying to free something that doesn't exist.发生的事情是你试图释放一些不存在的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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