-2

I'm new to c++ and I was trying to solve a c++ practise problem on hacker rank. After compiling I got the compiler message "Segmentation Fault" when trying to get the absolute difference between the sums of the two diagonals in a square matrix.

I have narrowed down the problem to line 8 but I don't know how to solve it.

int diagonalDifference(vector<vector<int>> arr) {
    int sumA,sumB;
    int n = arr.size();
    for (int i=0;i<n;++i) {
        sumA += arr[i][i];
        sumB += arr[n-i][n-i];
    }
    return abs(sumA - sumB);
}

I expect the output to be an absolute difference between the sum of the two diagonals in a square matrix.

  • Hint: what's the maximum index you can use in a vector with `n` elements? – Shawn Mar 27 '19 at 23:37
  • You will find that "practice problems" [from a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) will be far more useful, and informative. – Sam Varshavchik Mar 27 '19 at 23:41

1 Answers1

2

In C++ std::vectors (and almost everything else) are 0-indexed. So if a vector contains n elements, valid indices are 0 through to n-1. In your line

sumB += arr[n-i][n-i];

On the first iteration, i is 0. Therefore you're accessing arr[n][n], both indices are out of range, hence the segmentation fault.


Some other advice:

  • "segmentation fault" is not a compiler error (unless you're colossally unlucky or trying very hard), it's a runtime error.

  • "segmentation fault" means, basically, that you're trying to access or change some memory location you shouldn't be. Probably the most common is because you have a collection (vector, array, or similar) and you're using an out-of-range index (exactly your problem here).

  • C++ generally takes the attitude that things, correctly coded, should run as fast as they possibly can. Therefore, things like vector index checks aren't performed (because they'd slow things down slightly if the code were correct). This is why ugly and often hard-to-debug "segmentation faults" are relatively common.

JMAA
  • 1,730
  • 13
  • 24
  • 1
    Sidenote: The `std::vector::at` function does the bounds checking JMAA is talking about. Yes it is slower, but when debugging, it's worth the hit if you suspect you could be going out of bounds. `sumB += arr.at(n-i).at(n-i);` would throw an exception, you'd find the bug, and once you're sure you have fixed the problem, you switch back to using operator `[]` (if you need the speed). – user4581301 Mar 27 '19 at 23:52