c ++程序在执行两个等效语句时的意外行为

Unexpected behavior of c++ program on executing two equivalent statements

我正在尝试解决 this problem,

在这样做的同时, 看起来像

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

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

是等价的,但是执行后面的结果出现如下错误

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

我是不是漏掉了什么?提前谢谢你。

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);
 */

此声明

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

相当于ti

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

因此,例如,如果此表达式 (mat[i][col2] - (col1 != 0) ) 不等于 0 那么实际上您将有

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

即使 col1 等于 0.

你的意思好像是

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

注意这个功能

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

不安全。没有检查 row1、row2、col1 和 col2 是否在有效范围内。