2维数组释放 [英] 2-Dimensional array deallocation

查看:104
本文介绍了2维数组释放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个前奏,我用C ++在Visual Studio 2010中,编制了64位。我有一个使用2维数组来存储数据,通过一个C风格的函数,我没有控制权运行的程序:

 浮**的结果;
结果=新的浮动* [行]
的for(int i = 0; I<行++我){
    结果[I] =新的浮动[列];
}INT **数据;
数据= INT新* [行]
的for(int i = 0; I<行++我){
    数据由[i] =新的INT [列];
}//发送数据的功能和填充值的结果
ExternalFunction(*数据,*结果);//删除一切
的for(int i = 0; I<行-1 ++ I){
    删除[]和放大器;结果[I]。
    删除[]和放大器;数据[I]
}
删除[]的结果;
删除[]的数据;

这导致VS10通过一个调试断言失败与_BLOCK_TYPE_IS_VALID(PHEAD - > nBlockUse)。发生这种情况的节目的结束而不管实际发生在包含删除的最后几行。这是什么意思是什么呢?我究竟做错了什么?我觉得这是很简单,但我一直在寻找这个code太久。

- 编辑 -
问题解决了由于dasblinkenlight乐于助人的轻推到我的大脑!

 浮动*结果=新的浮动[*行列];
浮动*数据=新的浮动[*行列];ExternalFunction(安培;数据[0],&安培;结果[0]);删除[]的结果;
删除[]的数据;


解决方案

您code崩溃,因为你是传递一个地址的地址为删除[] ,这是不是你分配什么。更改code这样:

 的for(int i = 0; I<行++我){
    删除[]结果[I]。
    删除[]数据[I]
}

将不再崩溃。

在这个规则很简单:因为你分配新的的结果[..] 结果[I] ,你应该通过结果[I] ,而不是&安培;结果[I] ,到删除[] 。同样适用于数据

另外请注意,这code删除您分配的所有行,包括最后一个(现在的循环条件为 I< N ,而不是 I< N-1 )。感谢bjhend!

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;

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.

--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;

解决方案

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];
}

It will no longer crash.

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.

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!

这篇关于2维数组释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆