gpt4 book ai didi

检测到 C++ 堆损坏

转载 作者:行者123 更新时间:2023-11-28 00:17:01 25 4
gpt4 key购买 nike

我在运行教科书中的代码时遇到堆损坏错误。但是,当我通过在线编译器运行它时,它可以正常工作。我正在使用 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]。因此,您超出了数组的边界并导致堆损坏。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com