首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c++程序在执行两条等价语句时的意外行为

c++程序在执行两条等价语句时的意外行为
EN

Stack Overflow用户
提问于 2022-06-03 18:47:39
回答 1查看 54关注 0票数 1

我想解决这个问题问题,

在这样做的时候,看起来就像

代码语言:javascript
复制
for (int i=row1; i<=row2; i++) {
    if (col1 != 0) sum -= mat[i][col1-1];
    sum += mat[i][col2];
}

代码语言:javascript
复制
for (int i=row1; i<=row2; i++) {
    sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0);
}

是等价的,但是执行后的结果会导致以下错误

代码语言:javascript
复制
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:

代码语言:javascript
复制
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);
 */
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-03 18:54:54

这句话

代码语言:javascript
复制
sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0);

等于ti

代码语言:javascript
复制
sum += (mat[i][col2] - (col1 != 0) ) ? mat[i][col1-1] : 0;

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

代码语言:javascript
复制
sum += mat[i][col1-1];

即使col1等于0

看来你是说

代码语言:javascript
复制
sum += mat[i][col2] - ( (col1 != 0) ? mat[i][col1-1] : 0);

注意这个函数

代码语言:javascript
复制
int sumRegion(int row1, int col1, int row2, int col2) {

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72493969

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档