文章目录
一、AddressSanitizer:DEADLYSIGNAL
二、AddressSanitizer: SEGV on unknown address
三、heap-buffer-overflow on address 和 reference binding to misaligned address
四、runtime error: index -1 out of bounds for type...
五、warning: function returns address of local variable
前言
本篇是用来积累在LeetCode中出现的问题以及解决问题的文章。(请点击问题下的“分析与解决”)
一、AddressSanitizer:DEADLYSIGNAL
二、AddressSanitizer: SEGV on unknown address
三、heap-buffer-overflow on address 和 reference binding to misaligned address
四、runtime error: index -1 out of bounds for type...
五、warning: function returns address of local variable
六、执行代码返回结果正确,但提交解答却出错
这一类问题的出现,主要有几个原因:
a. 您的程序使用了全局变量或者自定义的类内变量。
力扣的判题机在读取您的代码后,对每个测试用例,都会初始化一次类,但全局变量和类内静态变量需要您手动初始化。例如,在第一题(两数之和)的判题过程中:
int globalVariable = 0;
class Solution {
public:
int classVariable = 0;
vector<int> twoSum(vector<int>& nums, int target) {
classVariable++;
globalVariable++;
return {classVariable, globalVariable};
};
};
这样的代码在运行两次test case后,输出的结果会是[1, 1], [1, 2]。
为了避免这样的问题,一般有两种解决方法:
1、避免申明类内静态变量以及全局变量。
2、在 twoSum 内对全局变量初始化。
b. 您的代码存在细微的问题,如变量没有初始化。
力扣 • 发表于:2018年10月26日 早上 00:33:03 • 更新于:2019年10月08日 下午 2:46:18
七、Line x: member access within null pointer of type 'struct TreeNode'
在leetcode上提交代码后出现编译错误:
Line x: member access within null pointer of type 'struct TreeNode'
原因:在测试过程中,第x行访问的指针为NULL,通常情况下表明程序未对NULL情况作出判断。例如:
int val = root->next->val;
在这一行中,没有加入root
及root->next
是否为空的判断,因此需修改为:
if (root != NULL) {
if (root->next != NULL) {
int val = root->next->val;
}
}
作者:Wasdns