gpt4 book ai didi

c++ - 更改索引顺序时堆损坏 C++

转载 作者:行者123 更新时间:2023-11-28 05:47:05 25 4
gpt4 key购买 nike

double*** RGB = new double**[4];
for (int i = 0; i < 4; i++)
{
RGB[i] = new double*[6];
for (int j = 0; j < 6; j++)
{
RGB[i][j] = new double[4];
}
}

std::vector<int> columnIndex(24);
std::vector<int> rowIndex(24);
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 4; j++)
{
columnIndex[i*4 + j] = i;
rowIndex[i*4+ j] = j;
}
}

for (int n = 0; n < 24; n++)
{
for (int ch = 0; ch < 3; ch++)
{
....
/*RGB[rowIndex[n]][columnIndex[n]][ch] = median;*/ //old line working
RGB[ch][rowIndex[n]][columnIndex[n]] = median; //new line causing the heap corruption ... I think
}
}

for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 6; j++)
{
delete[] RGB[i][j]; // crash is here when i and j are 0
}
delete[] RGB[i];
}
delete [] RGB;

更改前我的旧代码运行良好。我怎么注意到索引有问题,所以我必须进行修复。修复后我遇到了崩溃 - 我正在使用 Xunit。它说:

The thread 'Win64 Thread' (0x1f1c) has exited with code 0 (0x0).
HEAP[xunit.console.clr4.exe]: Heap block at 000000001D3C4820 modified at 000000001D3C4884 past requested size of 54
Windows has triggered a breakpoint in xunit.console.clr4.exe.

This may be due to a corruption of the heap, which indicates a bug in xunit.console.clr4.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while xunit.console.clr4.exe has focus.

最佳答案

使用我的调试器时,我注意到当您将值存储到您使用的 columnIndex 中时

columnIndex[i*4 + j] = i;

这给了你

0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5

当你去使用它的时候

RGB[ch][rowIndex[n]][columnIndex[n]] = median;

[columnIndex[n]] 将是 [0, 5] 但您只分配了 4 列

RGB[i][j] = new double[4];

它为您提供了 [0, 3] 的有效索引,因此您将离开数组的末尾。

看起来您需要做的就是在 columnIndexrowIndex 之间翻转 ij设置

for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 4; j++)
{
columnIndex[i * 4 + j] = j;
rowIndex[i * 4 + j] = i;
}
}

关于c++ - 更改索引顺序时堆损坏 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36017332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com