[英]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.