首页 > 解决方案 > 我怎样才能从这个“调试断言失败!”中找到我的编码错误在哪里?错误?

问题描述

我只是通过终端运行我的代码,然后“调试断言失败!” 弹出错误提示“向量下标超出范围”。这是我第一次遇到这种错误,所以我不确定如何在我的代码中找到错误所在。也许这很明显,因为我对 C++ 还很陌生,而且我不太擅长找出错误所在。以下是我的代码,所以如果您发现需要更正的内容,请告诉我。谢谢!

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

struct Node {
    int data;
    Node* right, * down;
};

Node* construct(vector<vector<int>> arr, size_t i, size_t j, size_t m, size_t n)
{
    if (i > n - 1 || j > m - 1)
        return NULL;
    Node * temp = new Node();
    temp->data = arr[i][j];
    temp->right = construct(arr, i, j + 1, m, n);
    temp->down = construct(arr, i + 1, j, m, n);
    return temp;
}

void display(Node * head)
{
    Node* Rp;

    Node* Dp = head;

    // loop till node->down is not NULL 
    while (Dp) {
        Rp = Dp;

        // loop till node->right is not NULL 
        while (Rp) {
            cout << Rp->data << " ";
            Rp = Rp->right;
        }
        cout << "\n";
        Dp = Dp->down;
    }
}

int main(int argc, char* argv[])
{


    if ((argc == 2) && (string(argv[1]) == "-Stack"))
    {
        int K;
        cin >> K; //getting the number of rooms from the text file



        for (int i = 0; i < K; ++i) //a loop for each room
        {
            int M = 0; // initializing rows variable
            int N = 0; // initializing columns variable
            cin >> M >> N;


            vector<vector<int> > matrix(M); //give a matrix with a dimension M*N with all elements set to 0
            for (int i = 0; i < M; i++)
                matrix[i].resize(N);

            for (int i = 0; i < M; i++) //adding each row to the matrix
            {
                for (int j = 0; j < N; j++) //adding each column to the matrix
                {
                    cin >> matrix[i][j]; //putting all the elements in the matrix
                }
            }

            size_t m = M, n = N;
            Node* head = construct(matrix, 0, 0, m, n);
            display(head);
            return 0;

        }

    }
    else if ((argc == 2) && (string(argv[1]) == "-Queue"))
    {
        int K;
        cin >> K; //this grabs the number of rooms in the dungeon
        cout << K;
    }
}

标签: c++runtime-error

解决方案


许多运行时错误并非发生在错误的确切位置,而是在您使用的调试工具的帮助下发生在某处。

例如,如果您尝试写入std::vector过去的大小,那么它的调试版本可能会进行边界检查并在其上抛出异常(调试器还插入堆栈帧陷阱以检查缓冲区溢出等)。

此异常不会出现在错误的确切行,而是出现在后面的代码中。

您可以使用调试器的调用堆栈功能来准确查找错误所在的位置。

例子:

vector<int> x(10);
x[10] = 1; // Calls vector::operator[] 
     // in vector::operator[]
     if(i >= size())
          throw; // This is where the exception is thrown

调用堆栈将帮助您从throw行转到x[10] = 1错误所在的行。


推荐阅读