检测到c++堆损坏

c++ heap corruption dectected

本文关键字:损坏 c++ 检测      更新时间:2023-10-16

我在运行课本中的代码时遇到堆损坏错误。然而,当我通过在线编译器运行它时,它是有效的。我正在使用visual studio 2013。我认为代码是正确的;我的视觉工作室可能出了问题吗?任何帮助都将不胜感激,谢谢!

#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]。因此,超出了数组的边界,就会导致堆损坏。