为什么运行时错误出现在我的代码中

why run time error is coming in my code?

本文关键字:我的 代码 运行时错误 为什么      更新时间:2023-10-16

我的代码是:

int main() {
    int t;
    cin >> t;
    while(t--){
        int ladder,snake,temp,x,y;
        cin >> ladder;
        vector<vector<int> >ar(ladder,vector<int> ());
        for(int i=0;i<ladder;i++){
            cin >> x >> y;
            ar[x].push_back(y);
        }
                cin >> snake;
        for(int i=0;i<snake;i++){
            cin >> x >> y;
            ar[x].push_back(y);
        }
    }
    return 0;
}

如果我输入

2
3
32 62
42 68
12 98
7
95 13
97 25
93 37
79 27
75 19
49 47
67 17
4
8 52
6 80
26 42
2 72
9
51 19
39 11
37 29
81 3
59 5
79 23
53 7
43 33
77 21

运行时错误来了,说内存管理不好。我的代码出了什么问题?

您将在数据序列之后看到问题

2
3
32 62

第一个值将被cin >> t吸收,并且为此可以忽略。

第二个值被cin >> ladder吸收,并导致ar被分配为3个int向量的向量。

第三行将被cin >> x >> y吸收,并用于将ar内部索引为ar[x].push_back(y)。由于x >= 3ar的大小,您将写入未分配的内存,这将在稍后导致崩溃。

使用g++ -D_GLIBCXX_DEBUG -g -Wall test.cpp编译的代码也将输出;

/usr/include/c++/4.9/debug/vector:357:error: attempt to subscript container
    with out-of-bounds index 32, but container only holds 3 elements.

Joachim Isaksson提供了一个很好的答案,但问题似乎比这个更深。在试图弄清楚发生了什么时,我发现了这个神奇的解决方案。像这样打开你的主循环:

int main() {
    int t;
    cout << "This is a fix. Crazy, huh?n";
    cin >> t;

老实说,我不能告诉你发生了什么,但这一次对cout的调用阻止了程序在我的机器上出错。每一个仅有一个的时间

相关文章: