c++ - 执行在 push_back 处停止
问题描述
下面的 for 循环在第一个循环中停止执行,我不知道为什么。我通过在其中放置 couts 发现它在 push_back 处停止。它以前可以工作,然后我尝试修改它,然后我按 Ctrl-z 使其恢复到此状态,现在它突然停止在 push_back 时似乎以前没有。到底是怎么回事?
#include <iostream>
#include <vector>
using namespace std;
void decode(int[], int, int[][2]);
void displayArray(int[], int);
int main()
{
const int SIZE = 12;
int test[SIZE-2] = {3,9,1,4,8,0,11,5,1,8};
int edgeList[SIZE-1][2];
for (int i = 0; i < SIZE -1; i++)
{
edgeList[i][0] = -1;
edgeList[i][1] = -1;
}
decode(test, SIZE, edgeList);
return 0;
}
void decode(int inputString[], int size, int edgeList[][2])
{
int** arrayC = new int*[size - 2];
for(int i = 0; i < size - 2; i++)
arrayC[i] = new int[2];
for (int i = 0; i < size -2 ; i++)
{
arrayC[i][0] = i+1;
arrayC[i][1] = inputString[i];
}
for (int i = 0; i < size - 2; i++)
{
displayArray(arrayC[i], 2);
}
for (int i = 0; i < size - 1; i++)
{
vector<int> currentCycle;
int *visited = new int[size - 2];
for(int j = 0; j < size - 1; j++)
{
visited[j] = 0;
}
bool repeat = false;
int currentIndex = i;
while(!repeat)
{
int curElem = arrayC[currentIndex][0];
if (!visited[curElem] && curElem != 0 && curElem != size - 1)
{
cout << curElem << endl;
currentCycle.emplace_back(curElem);
visited[curElem] = 1;
}
else
{
repeat = true;
}
currentIndex = arrayC[currentIndex][1] - 1;
if (currentIndex == -1 || currentIndex == size -2)
{
repeat = true;
currentCycle.push_back(-1);
}
}
for (int i = 0; i < currentCycle.size(); i++)
cout << currentCycle[i] << " ";
cout << endl;
delete visited;
}
}
void displayArray(int array[], int size)
{
for (int i = 0; i < size; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
解决方案
int *visited = new int[size - 2];
size
是 12。这分配了一个由 10 个整数组成的数组:visited[0]
通过visited[9]
.
for(int j = 0; j < size - 1; j++)
此for
循环j
从 0 迭代到 10。size - 1
为 11。j
因此,此循环中的最后一个值为 10。
visited[j] = 0;
这最终将尝试设置visited[10]
为 0。
失败。visited
数组太小了。只有visited[0]
通过visited[9]
才有效。这会导致内存损坏和未定义的行为。
这可能是也可能不是所示代码中的唯一错误。这是第一个使用valgrind轻松发现的内存访问违规,这是一个很棒的静态内存分析工具,它在内存损坏发生时停止了该程序的执行,允许我用我的调试器闯入程序,检查所有变量的值,并轻松识别问题所在。
花一些时间学习如何使用调试和诊断工具(例如这些工具)是值得的。它们确实可以帮助您非常快速地找到自己代码中的错误。
代码的总体目的不是很清楚,所以正确的修复应该是什么并不明显,所以我在找到第一个显示停止后就停下来了。正如我简要提到的,在解决此问题后,可能还会出现其他类似的问题。如果是这样,您应该能够以与我相同的方式找到它们,并借助一些您可能已经拥有的有用工具的帮助。
推荐阅读
- c# - 当我尝试使用我的 Google 服务帐户通过 Gmail API 发送电子邮件时,“myemail@mydomain.com”的委派被拒绝
- python - 如何删除一封邮件?
- spring-boot - Fire Store 插入批量数据不一致
- c# - 使用适用于 ASP.NET 的 firebase SDK 处理登录
- postgresql - 如何释放 plpgsql 中的内存?
- python - Setuptools 在卸载时删除手动添加的文件
- solana - Solana - 如何确定最终性
- image - Vue - 根据屏幕大小更改 URL 图像路径
- mysql - 棘手的 MYSQL ORDER BY 子句
- haskell - 作为语言的类型求幂的定点