【发布时间】:2012-04-25 01:45:12
【问题描述】:
我目前正在寻找两个矩阵的平方距离之和,数据保存在 double* 数组中。它们中的第一个保持不变,而另一个循环使用返回两个索引之间的 32x32 数组的函数。
但是,当我尝试在“e”的第一次递增之后调用“getTile(d,e)”时,它会引发堆损坏异常:
double* Matrix::ssd(int i, int j, Matrix& rhs){
double sum = 0, val = 0; int g = 0, h=0;
double* bestMatch = new double[32*32]; double* sameTile = new double[32*32]; double* changeTile = new double[32*32];
for(int x = i-32; x <i; x++){
for(int y = j-32; y <j; y++){
sameTile[g*32+h] = data[x*N+y];
h++;
}g++; h = 0;
}
system("pause");
for(int d = 32; d<=512; d+=32){
for(int e = 32; e<=512; e+=32){
changeTile = rhs.getTile(d,e);
for(int out = 0; out < 32; out++){
for(int in = 0; in < 32; in++){
val = sameTile[out*32+in] - changeTile[out*32+in];
val = val*val;
sum = sum + val;
}
}
cout << sum << endl;
sum = 0; val = 0;
system("pause");
}
}
getTile(int i, int j) 函数:
double* Matrix::getTile(int i, int j){
double* tile = new double[32*32]; int g = 0; int h = 0;
for(int x=i-32; x<i; x++){
for(int y=j-32; y<j; y++){
tile[g*32+h] = data[x*N+y];
h++;
}
cout << endl;
g++;
}
return tile;
}
我相信 changeTile double* 中的内存分配会发生错误?
非常感谢任何帮助。
【问题讨论】:
-
什么是 N 以及输入到 ssd() 方法的输入 i 和 j 是什么? data[] 的定义/大小也会有所帮助。
-
tile似乎是returned fromgetTile()没有任何数据写入其中。这是故意的吗? -
如果您坚持每行一个语句而不是像
double* tile = new double[32*32]; int g = 0; int h = 0;那样尝试将它们挤进去,那么您的代码阅读起来会更清晰@d?您是否考虑过智能指针或任何std::容器?double*s 不是“数组”,它们是指针,应该这样对待。 -
@uesp N 是 x 轴的大小,在本例中为 512。使用 N 和 M 声明数据,如: double* data = new double[M*N];输入 i 和 j 指定正在针对 rhs 矩阵中的每个图块进行测试的 32x32 图块的位置
-
改正后的程序还有bug吗?
标签: c++ matrix double heap-corruption