无法为此代码调试分段错误

问题描述

这是来自在线hackerrank在线平台的问题。 Nikita and the Game

我对此进行了编码,而我的解决方案仅通过了给定的测试用例,这在提交时给其他测试用例带来了分段错误
我将我的方法与编辑解决方案进行了比较,其中一种解决方案使用了与我的方法相同的方法二进制搜索方法来找到可以分割数组的索引)。

但是我不知道为什么会出现细分错误

#include <bits/stdc++.h>
#define lld long long

using namespace std;


lld isPossible(vector<lld>&pre_sum,lld start,lld end){
    
    lld low = start-1;
    lld high = end;
    
    while(start<=end){
        lld mid = (start+end)/2;
        lld left_sum = pre_sum[mid] - pre_sum[low];
        lld right_sum = pre_sum[high]- pre_sum[mid];
        
        if(left_sum == right_sum) return mid;
        if(left_sum < right_sum) start = mid+1;
        if(left_sum > right_sum) end = mid-1;
    }
    return -1;
}

lld calcAns(vector<lld>&pre_sum,lld end){
    //cout<<start<<" "<<end<<"\n";
    lld idx = isPossible(pre_sum,start,end);
    //cout<<idx<<"\n";
    if(idx == -1) return 0;
    return 1 + max(calcAns(pre_sum,idx),calcAns(pre_sum,idx+1,end));
    
}
/*
 * Complete the arraySplitting function below.
 */
lld arraySplitting(vector<lld> arr) {
    
    vector<lld> pre_sum(arr.size() + 1);
    pre_sum[0] = 0;
    
    for(lld i=0; i<arr.size(); i++){
        pre_sum[i+1] = pre_sum[i] + arr[i]; 
    }
    
    lld ans = calcAns(pre_sum,1,pre_sum.size()-1);
    //cout<<ans<<"\n";
    return ans;
}

int main()
{

    lld t;
    cin >> t;

    for (lld t_itr = 0; t_itr < t; t_itr++) {
        lld arr_count;
        cin >> arr_count;

        vector<lld> arr(arr_count);

        for (lld arr_itr = 0; arr_itr < arr_count; arr_itr++) {
            lld arr_item;
            cin>>arr_item;
            arr[arr_itr] = arr_item;
        }

        lld result = arraySplitting(arr);

        cout << result << "\n";
    }

    return 0;
}

代码说明:

isPossible 函数查找索引,该索引的数组的左部分 [start....mid]等于右部分 [mid+1.....end]

calcAns 计算可能的此类索引的编号,其方式为一旦找到该索引,它将忽略一个部分,而在另一部分中查找任何此类可能的索引。它将计算最大编号。这种可能的分裂。

arraySplitting 仅计算前缀和数组pre_sum,并且比实际数组大一号,即第一个索引的和为零,因此它将稍后在计算范围之间的总和时简化计算。它会调用 calcAns 函数进行进一步处理。

编辑:我想学习调试案例,而不必实际使用调试器,因为在提交竞赛期间无法下载测试用例。因此,当我开始为编程比赛训练自己时,我想了解我缺少的东西会导致细分错误。如果有人可以看到代码预言这些类型的tescase是可能的,而我的代码可能会给出分段错误,则将很有帮助。这正是我真正要寻找的东西,否则在比赛结束后使用gdb设置断点来调试大型测试用例并没有任何好处。

解决方法

解决此问题的第一步是确定段错误发生的位置。

您可以使用gdb,step,设置断点等来调试程序。

还按照注释中的建议添加调试指令。

您可以在方法中添加防御性检查,例如将索引lowmidhigh与向量的大小进行比较。向量容量设置也可能会导致内存不足异常,因此您还应该在代码周围添加try-except处理程序。

或者,您可以使用一个库来捕获段错误并提供堆栈跟踪,以便您可以查看段错误的起源,例如 https://github.com/certik/stacktrace

另请参阅相关问题,例如how to debug c++ runtime errors