Search code examples
c++c++11exitstatus

Exit Status -1 on C++ Program


When executed, my code gives an exit status -1. I can show the input if it makes any difference. Can anybody find why this is happening?

INPUT:

6

N 10

E 2

S 3

W 4

S 5

E 8

I have already looked at the 2D integer array, and the variables in my code, looking for uninitialized ones, but I found no such errors. Can anybody see why I am getting exit status -1?

#include <iostream>
#include <algorithm>
#include <fstream>
using namespace std;

int main() {
  ofstream fout("mowing.out");
  ifstream fin("mowing.in");
  int n; fin >> n;
  int ans = 0;
  int field[2003][2003];
  for (int i = 0; i < 2003; i++) {
    for (int j = 0; j < 2003; j++) {
      field[i][j] = 0;
    }
  }
  int xloc = 1001, yloc = 1001, time = 0;
  for (int i = 0; i < n; i++) {
    char dir; int steps;
    fin >> dir >> steps;
    if (dir == 'N') {
      for (int j = 1; j < steps; j++) {
        yloc++;
        time++;
        if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
        field[xloc][yloc] = time;
      }
    }
    if (dir == 'S') {
      for (int j = 1; j < steps; j++) {
        yloc--;
        time++;
        if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
        field[xloc][yloc] = time;
      }
    }
    if (dir == 'W') {
      for (int j = 1; j < steps; j++) {
        xloc--;
        time++;
        if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
        field[xloc][yloc] = time;
      }
    }
    else {
      for (int j = 1; j < steps; j++) {
        xloc++;
        time++;
        if (field[xloc][yloc] != 0) ans = max(ans, time-field[xloc][yloc]);
        field[xloc][yloc] = time;
      }
    }
  }
  if (ans == 0) fout << -1 << "\n";
  else fout << ans << "\n";
  return 0;
}

Solution

  • On top of excellent points made by bruno, I believe the root cause of the problem you encounter is a (nomen omen!) stack overflow.

    Your array is too big to place on stack. Quick calculations (assuming sizeof(int) == 4):

    2003 * 2003 * 4 B = 16048036 B = 15671.91015625 KiB = 15.304599761962890625 MiB
    

    You're trying to allocate 15.3 MiB of memory on stack, whereas, according to this question, by default Windows allows 1 MiB and Linux usually allows 8 MiB.

    You should either allocate memory on the heap by yourself or (better) use std::vector, like this:

    std::vector<std::vector<int>> field (2003, std::vector(2003));
    //it is already initialized above, no need for for loops ;)
    //later on it can be used like regular array in most of the cases