为什么运行时错误出现在我的代码中
why run time error is coming in my code?
我的代码是:
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 >= 3
是ar
的大小,您将写入未分配的内存,这将在稍后导致崩溃。
使用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的调用阻止了程序在我的机器上出错。每一个仅有一个的时间
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 为什么我的代码在输出中增加了93天
- 0-1背包代码中的错误.我的代码中有什么错误
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 为什么我的C++代码中出现'Segmentation Fault: 11'行?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- 我的代码运行良好,但在游戏循环中中断
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?
- 我认为我的代码很好,但它在 cin a 之后停止并且没有进一步?
- 我的代码中的意外价值以及我如何修复它
- 为什么 rand 不在我的代码中生成随机数?
- 编写了一个C++代码来检查表达式是否具有平衡括号并且我的代码未运行.我已经卡了一天了
- 如何改进我的代码,使其不会因超时而终止?(黑客排名挑战)
- 无法找出我的代码中的内存泄漏
- 我不明白为什么我的代码不起作用并且需要更长的时间来运行
- 我正在尝试创建一个菜单,但我的代码一直在循环