LeetCodeBug-Runtime Error Message: reference binding to null pointer of type 'struct value_type'

写在前面:

这个Bug是在我做LeetCode题目时遇到的,以前也遇到过,这个问题也不大,但还是积累一下。

错误提示:

LeetCode编辑器提示的错误如下:

"Runtime Error Message:reference binding to null pointer of type 'struct value_type'
Last executed input: []

翻译一下,错误含义如下:

  1. 提示运行时间错误:引用绑定到类型为“struct value_type”的空指针。
  2. 上一个错误输入是:[]。

错误原因:

这个Bug是在LeetCode题目中: LeetCode-26. Remove Duplicates from Sorted Array。出现的。

首先要说明错误提示的含义,就是说程序是在输入为:[],的时候出现的bug。所以要明白这个意思。

然后就是明白LeetCode测试系统的原理。在这道题中,我们只返回count的值,LeetCodeOJ会根据我返回的count的值来取nums中对应的元素来判断答案是否正确。

而在我的错误代码中,我返回:

return count+1;

count初值为0,当输入[]时,循环体条件不符合,直接跳过,那么返回值为:0+1=1.但是这时候系统会去查nums中的索引为0,1的元素,但是nums为[],所以就会出现这样的bug。

解决方法:

解决方法也如题目中的解法二所示,将返回值改为:

int len=nums.size();
return len==0?count:count+1;

就是要判断输入的nums的长度是不是为0,如果是0,直接返回0,不是0,就返回count+1.

此外,Runtime Error Message: reference binding to null pointer of type ‘struct value_type’,以便对这个错误有个更全面的认识。

你可能感兴趣的:(Bug,And,Debug)