【问题标题】:Understanding the reason of segmentation fault in code snippet below [closed]了解以下代码片段中分段错误的原因[关闭]
【发布时间】:2021-01-15 01:00:43
【问题描述】:

我正在尝试找出数组中最长的峰值长度。

示例: 数组:[1, 2, 3, 2, 1, 1] 峰值长度:5 (1,2,3,2,1)

我使用以下代码找出数组中最长的峰值:

using namespace std;

int longestPeak(vector<int> array) {
    int longestPeak = 0;
    int idx = 1;
    
*`//In the while loop below, if I change the condition to (idx < (array.size() - 1)), it throws a segmentation fault'*
    while (idx < int(array.size() - 1)){
        bool isPeak = array[idx] > array[idx - 1] and array[idx] > array[idx + 1];
        if (!isPeak){
            idx += 1;
            continue;
        }
        
        int leftIdx = idx - 2;
        while (leftIdx >= 0 and array[leftIdx] < array[leftIdx + 1])
            leftIdx -= 1;
        
        int rightIdx = idx + 2;
        while (rightIdx < array.size() and array[rightIdx] < array[rightIdx - 1])
            rightIdx += 1;
        
        int currentPeak = rightIdx - leftIdx - 1;
        longestPeak = max(currentPeak, longestPeak);
        idx = rightIdx;
    } 
    return longestPeak;
}

在下面的第一个 while 循环中,如果我将条件更改为 (idx

请帮助我了解此问题背后的原因。

【问题讨论】:

  • 您是否尝试过在调试器中逐行运行代码,同时监控所有变量的值,以确定您的程序在哪个点停止按预期运行?如果您没有尝试过,那么您可能想阅读以下内容:What is a debugger and how can it help me diagnose problems? 您可能还想阅读以下内容:How to debug small programs?
  • 提供的代码没有给我提供的输入 (1, 2, 3, 2, 1, 1) 的分段错误。请提供包含触发此崩溃的输入的minimal reproducible example。对于奖励积分,请确定发生崩溃的行以及该点的变量值。
  • 另外,提供的代码不会在没有警告的情况下编译。见Why should I always enable compiler warnings?
  • @Peter 在访问array[leftIdx]之前检查条件leftIdx &gt;= 0
  • 谢谢大家,我通过调试器运行了我的代码。我的问题与作为输入的空数组有关,其中存在 unsigned int 溢出。

标签: c++ arrays data-structures segmentation-fault


【解决方案1】:

有未签名的促销:0u - 1unsigned int 的最大价值。

所以idx &lt; int(array.size() - 1) 为正的idx 和空的array

【讨论】:

  • 嗯,array 没有在循环中被修改,所以除非 OP 调用具有空范围的函数(这不是所述输入所暗示的),否则这不是原因为崩溃。
  • 感谢您的回复,能否请您详细说明一下,以便我有一个清楚的了解。我仍然无法弄清楚这里的原因。
  • 谢谢大家,我通过调试器运行了我的代码。我的问题与作为输入的空数组有关,其中存在 unsigned int 溢出。
猜你喜欢
  • 2014-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
  • 2021-04-09
  • 1970-01-01
  • 2014-10-30
  • 2013-06-11
相关资源
最近更新 更多