从教科书中运行代码时遇到堆损坏错误,但是当我通过在线编译器运行它时,它可以工作。我正在使用Visual Studio2013。我认为代码是正确的;我的视觉工作室可能有问题吗?任何帮助将不胜感激,谢谢!

#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]。因此,您超出了数组的范围,并导致堆损坏。

关于c++ - 检测到c++堆损坏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29561581/

10-12 17:16