检测到 C++ 堆损坏

c++ heap corruption dectected

当我 运行 从我的 textbook.However 中获取代码时,我收到堆损坏错误,当我通过在线编译器 运行 它时,它可以工作。我正在使用 visual studio 2013。我认为代码是正确的;会不会是我的 visual studio 出了什么问题?任何帮助将不胜感激,谢谢!

#include <iostream>
#include<cstdlib>
#include<ctime>
#include<iomanip>
using namespace std;

int main() {
    // your code goes here
    srand(time(0));
    int* counts[10];
    // Allocate the rows
    for (int i = 0; i < 10; i++)
    {
        counts[i] = new int[i + 1];
        for (int j = 0; j <= 1; j++)
        {
            counts[i][j] = 0;
        }
    }
    const int RUNS = 1000;
    // Simulate 1,000 balls
    for (int run = 0; run < RUNS; run++)
    {
        // Add a ball to the top
        counts[0][0]++;
        // Have the ball run to the bottom
        int j = 0;
        for (int i = 1; i < 10; i++)
        {
            int r = rand() % 2;
            // If r is even, move down,
            // otherwise to the right
            if (r == 1)
            {
                j++;
            }
            counts[i][j]++;
        }
    }
    // Print all counts
    for (int i = 0; i < 10; i++)
    {
        for (int j = 0; j <= i; j++)
        {
            cout << setw(4) << counts[i][j];
        }
        cout << endl;
    }
    // Deallocate the rows
    for (int i = 0; i < 10; i++)
    {
        delete[] counts[i];
    }

    return 0;
}

这里

 for (int i = 0; i < 10; i++)
    {
        counts[i] = new int[i + 1];
        for (int j = 0; j <= 1; j++)
        {
            counts[i][j] = 0;
        }
    }

对于 counts[0] 你只为一个 int (counts[0] = new int[0+1]) 分配内存。在内部循环中,您尝试访问 counts[0][1]。因此,您超出了数组的边界并导致堆损坏。