考虑以下代码
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, k;
cin >> n >> k;
vector<int> a(n);
int sum = 0;
for (auto &it : a) {
cin >> it;
sum += it;
}
cout << sum << "\n";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
输入,例如(或在k到k中大于int_max的内容)
5 1234567891564
1 2 3 4 5
使程序打印
0
0 0 0 0 0
实际发生了什么?我们根本不使用k
的值。
Consider the following code
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, k;
cin >> n >> k;
vector<int> a(n);
int sum = 0;
for (auto &it : a) {
cin >> it;
sum += it;
}
cout << sum << "\n";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
Input like (or anything greater than INT_MAX into k)
5 1234567891564
1 2 3 4 5
makes the program print
0
0 0 0 0 0
What actually happens? We don't use the value of k
at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码实际上没有整数溢出。从更广泛的意义上讲,它存在,但是从更狭窄的意义上讲,整数溢出将发生:
实际发生的是,在此行中,
操作员&gt;&gt;
试图读取int int
但失败。1234567891564
实际上从未分配给k
。阅读输入时,将分配0
。因此,k
以0
出现。一旦流处于错误状态,所有随后的调用
operator&gt;
也将默默失败。输入后,您应始终检查流的状态。例如:There is actually no integer overflow in your code. Well in a wider sense it there is, but in a more narrow sense integer overflow would happen for example with:
What actually happens is that in this line
operator>>
tries to read aint
but fails.1234567891564
is never actually assigned tok
. When reading the input fails0
will be assigned. Hencek
comes out as0
.Once the stream is in an error state, all subsequent calls to
operator>>
will silently fail as well. You should always check the state of the stream after taking input. For example: