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

heap corruption when changing index order c++

本文关键字:损坏 C++ 索引 顺序      更新时间:2023-10-16
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] indes,因此您将离开数组的末尾。

看起来您需要做的就是在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;
    }
}