由vector的size()函数引发的越界问题

9 篇文章 0 订阅

由vector的size()函数引发的越界问题

在做剑指 Offer 04. 二维数组中的查找一题时,如下代码:

class Solution {
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        int i = matrix.size() - 1, j = 0;
        while (i >= 0 && j <= matrix[0].size() - 1) {
            if (matrix[i][j] > target) i--;
            else if (matrix[i][j] < target) j++;
            else return true;
        }
        return false;
    }
};

在执行[[]],1这个测试用例时,会出现如下错误:

Line 1033: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9

根据网上查阅的资料得知是发生了数组越界,matrix[i][j]当然会发生数组越界,越界在意料之中,疑惑的地方在于为什么程序仍然能够进入循环体导致越界?

while的判断条件也很简单,两个变量都和vectorsize()函数有关。

_NODISCARD size_type size() const noexcept { // return length of sequence
    auto& _My_data = _Mypair._Myval2;
    return static_cast<size_type>(_My_data._Mylast - _My_data._Myfirst);
}

在C++ reference中对vectorsize_type的介绍如下:

an unsigned integral type that can represent any non-negative value of difference_type

size()函数的返回值size_type本质上是一个无符号整型,因此,在j <= matrix[0].size() - 1matrix[0].size() - 1不是我们认为的结果-1,而是将-1的补码按照无符号整型转换成的一个很大的值(常识:计算机使用补码进行运算),因此,也就解释了为什么程序能够进入循环体导致数组越界了。

在这里插入图片描述

因此,需要对matrix[0].size()做一下类型转换,下面的代码就可以成功通过测试用例了。

class Solution {
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        int i = matrix.size() - 1, j = 0;
        while (i >= 0 && j <= (int)matrix[0].size() - 1) {
            if (matrix[i][j] > target) i--;
            else if (matrix[i][j] < target) j++;
            else return true;
        }
        return false;
    }
};

当然,如果提前对参数进行判空也就不会出现上述问题了,可见良好编程规范的重要性!

class Solution {
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        if (matrix.size() == 0 || matrix[0].size() == 0) {
            return false;
        }
        int i = matrix.size() - 1, j = 0;
        while (i >= 0 && j <= (int)matrix[0].size() - 1) {
            if (matrix[i][j] > target) i--;
            else if (matrix[i][j] < target) j++;
            else return true;
        }
        return false;
    }
};

Reference

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值