Home > database >  Is integer overflow that evil?
Is integer overflow that evil?

Time:06-02

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.

CodePudding user response:

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:

int k = 1234567891564;

What actually happens is that in this line

cin >> n >> k;

operator>> tries to read a int but fails. 1234567891564 is never actually assigned to k. When reading the input fails 0 will be assigned. Hence k comes out as 0.

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:

 if (std::cin >> n) {
     // input succeeded use the value 
 } else {
     // input did not succeed. 
     std::cin.clear(); // reset all error flags
 }        
  • Related