二维数组释放 [英] 2-Dimensional array deallocation
问题描述
作为介绍,我在 Visual Studio 2010 中使用 C++,针对 x64 进行编译.我有一个程序使用二维数组来存储数据以运行我无法控制的 C 风格函数:
As an intro, I'm using C++ in Visual Studio 2010, compiling for x64. I have a program that's using 2-Dimensional arrays to store data for running through a C style function that I have no control over:
float **results;
results = new float*[rows];
for (int i = 0; i < rows; ++i){
results[i] = new float[columns];
}
int **data;
data = new int*[rows];
for (int i = 0; i < rows; ++i){
data[i] = new int[columns];
}
//send data to the function and populate results with values
ExternalFunction(*data, *results);
//delete everything
for (int i = 0; i < rows-1; ++i){
delete [] &results[i];
delete [] &data[i];
}
delete [] results;
delete [] data;
这会导致 VS10 通过 _BLOCK_TYPE_IS_VALID(pHead -> nBlockUse) 的调试断言失败.无论在包含删除的最后几行中实际发生了什么,这都会在程序结束时发生.这究竟是什么意思?我究竟做错了什么?感觉真的很简单,但是这段代码看的太久了.
This causes VS10 to through a Debug Assertion Failure with _BLOCK_TYPE_IS_VALID(pHead -> nBlockUse). This happens by the end of the program regardless of what really happens in the last few lines containing the deletes. What does this mean exactly? What am I doing wrong? I feel like it's really simple, but I've been looking at this code for too long.
--编辑---由于 dasblinkenlight 对我大脑的帮助,问题解决了!
--EDIT--- Problem solved thanks to dasblinkenlight's helpful nudge to my brain!
float *results = new float[rows * columns];
float *data = new float[rows * columns];
ExternalFunction(&data[0], &results[0]);
delete [] results;
delete [] data;
推荐答案
您的代码崩溃,因为您将地址的地址传递给 delete[]
,而这不是您分配的.将您的代码更改为:
Your code crashes because you are passing an address of an address to delete[]
, which is not what you allocated. Change your code to this:
for (int i = 0; i < rows ; ++i){
delete [] results[i];
delete [] data[i];
}
它不会再崩溃了.
这方面的规则很简单:由于您将 new[..]
的结果分配给 results[i]
,您应该传递 results[i]
,而不是 &results[i]
,要删除 []
.data
也是如此.
The rule on this is simple: since you assigned the results of new[..]
to results[i]
, you should be passing results[i]
, not &results[i]
, to delete []
. Same goes for data
.
还要注意,这段代码会删除您分配的所有行,包括最后一行(循环条件现在是 i
i
Also note that this code deletes all rows that you allocated, including the last one (the loop condition is now i < n
, not i < n-1
). Thanks bjhend!
这篇关于二维数组释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!