Evil Integer Overflow

Revision en1, by Destopia, 2022-05-24 03:59:39

Consider 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.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English Destopia 2022-05-24 03:59:39 681 Initial revision (published)