Home > other >  Unexpected behavior of c program on executing two equivalent statements
Unexpected behavior of c program on executing two equivalent statements

Time:06-04

I was trying to solve this problem,

while doing so, it looks like

for (int i=row1; i<=row2; i  ) {
    if (col1 != 0) sum -= mat[i][col1-1];
    sum  = mat[i][col2];
}

and

for (int i=row1; i<=row2; i  ) {
    sum  = (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0);
}

are equivalent, but executing the later results in following error

Line 1038: Char 34: runtime error: addition of unsigned offset to 0x618000000080 overflowed to 0x61800000007c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c  /9/bits/stl_vector.h:1043:34

Am I missing something?, Thank You In Advance.

complete program:

class NumMatrix {
public:
    vector<vector<int>> mat;
    NumMatrix(vector<vector<int>>& matrix) {
        mat = matrix;
        for (int i=0; i<matrix.size(); i  ) {
            for (int j=1; j<matrix[0].size(); j  )
                mat[i][j]  = mat[i][j-1];
        }
    }
    
    int sumRegion(int row1, int col1, int row2, int col2) {
        int sum = 0;
        for (int i=row1; i<=row2; i  ) {
            if (col1 != 0) sum -= mat[i][col1-1];
            sum  = mat[i][col2];
            
            // sum  = (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0); // this gives error :
            // Line 1038: Char 34: runtime error: addition of unsigned offset to 0x618000000080 overflowed to 0x61800000007c (stl_vector.h)
            // SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c  /9/bits/stl_vector.h:1043:34
        }
        
        return sum;
    }
};

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix* obj = new NumMatrix(matrix);
 * int param_1 = obj->sumRegion(row1,col1,row2,col2);
 */

CodePudding user response:

This statement

sum  = (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0);

is equivalent ti

sum  = (mat[i][col2] - (col1 != 0) ) ? mat[i][col1-1] : 0;

So for example if this expression (mat[i][col2] - (col1 != 0) ) is not equal to 0 then you will have in fact

sum  = mat[i][col1-1];

even when col1 is equal to 0.

It seems you mean

sum  = mat[i][col2] - ( (col1 != 0) ? mat[i][col1-1] : 0);

Pay attention to that this function

int sumRegion(int row1, int col1, int row2, int col2) {

is unsafe. There is no check whether row1, row2, col1 and col2 are in valid ranges.

  • Related