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

时间:2016-03-15 16:49:10

标签: c++

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.

1 个答案:

答案 0 :(得分:1)

使用我的调试器时,我注意到将值存储到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,因此您将离开数组的末尾。

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

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