首页 > 解决方案 > 执行在 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;
}

标签: c++vectorpush-back

解决方案


    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轻松发现的内存访问违规,这是一个很棒的静态内存分析工具,它在内存损坏发生时停止了该程序的执行,允许我用我的调试器闯入程序,检查所有变量的值,并轻松识别问题所在。

花一些时间学习如何使用调试和诊断工具(例如这些工具)是值得的。它们确实可以帮助您非常快速地找到自己代码中的错误。

代码的总体目的不是很清楚,所以正确的修复应该是什么并不明显,所以我在找到第一个显示停止后就停下来了。正如我简要提到的,在解决此问题后,可能还会出现其他类似的问题。如果是这样,您应该能够以与我相同的方式找到它们,并借助一些您可能已经拥有的有用工具的帮助。


推荐阅读