【问题标题】:AddressSanitizer: heap-buffer-overflow on address LeetcodeAddressSanitizer:地址 Leetcode 上的堆缓冲区溢出
【发布时间】:2022-11-14 03:20:56
【问题描述】:

我正在尝试解决有关 Leetcode 的问题。link 我是 C++ 新手,我想弄清楚为什么会出现这个错误。谷歌搜索说我试图越界访问数组/向量,但我不知道在哪里。

class Solution {
public:
    // Binary Search Function , returns index
    int binarySearch(vector<int> nums, int l, int r, int target)
    {
        while (l <= r)
        {
            int mid = (l + r) / 2;
            if (nums[mid] == target)
                return mid;
            else if (nums[mid] < target)
                l = mid + 1;
            else if (nums[mid] > target)
                r = mid - 1;
        }
        return -1;
    }
    int search(vector<int>& nums, int target) {
        int n = nums.size();
        int smallest = nums[0]; 
        for (int i = 1; i < n; i++) // finds the smallest element of rotated sorted array 
        {
            if (nums[i] < nums[i - 1])
            {
                smallest = i;
                break;
            }
        }
        if (target >= nums[smallest] && target <= nums[n - 1]) // apply binary search in 2nd half
            return binarySearch(nums, smallest, n - 1, target);
        else if (target >= nums[0] && smallest>0 && target <= nums[smallest - 1] ) // apply binary search in 1st half
            return binarySearch(nums, 0, smallest - 1, target);
        return -1;
    }
};

谁能解释我做错了什么? 以及将来如何避免此类错误?

【问题讨论】:

  • 这种组合似乎很可疑int smallest = nums[0];,其次是target &gt;= nums[smallest]。您正在使用数组中的最小值作为索引进入数组。例如,如果数组包含负数怎么办。
  • 这个问题的代码/措辞很可能来自无数编码挑战/拼图网站之一。他们通过提供基于神秘知识或编程技巧的编码难题来利用想要学习 C++ 的人;再加上解决那些无用的编码难题使任何人都成为 C++ 专家的说法。当然,这是不真实的,但是如果不知道某些神秘的技巧,这些编码难题(没有学习或现实价值)是无法解决的。每个人最终都弄清楚了这个骗局,但只是在很长一段时间之后,没有什么可证明的。
  • 我是 C++ 新手Leetcode 是用来解决随机问题的,绝对不是用来学习 C++ 的。
  • 你无法避免编程错误,编程太难了。您可以做的是学习如何有效地使用调试器尽快修复这些错误。
  • 当您收到这样的报告时,有一些不错的选择可以帮助您缩小范围。一种是暂时将[] 的使用换成at 方法,并选择调试器抛出的异常。一些库实现有一个调试标志,您可以使用它来启用额外的运行时检查,您可以使用调试器捕获和检查。许多工具链都包含法官使用的相同消毒剂,因此您可以自己打开它们。有时他们可以告诉你所有你需要知道的事情,直到行号。

标签: c++ binary-search buffer-overflow


【解决方案1】:

这看起来像你的错误:

    int smallest = nums[0]; 

应该:

    int smallest = 0; 

这可能是不正确的:

            smallest = i;
            break;          // Why are you breaking out of the loop?
                            // There may ne another smaller number yet to be found

【讨论】:

  • 我是一个白痴。谢啦!解决了它。另外,我打破了循环,因为只有一次这样的情况会发生,因为数组已排序并且具有不同的元素。
猜你喜欢
  • 2019-01-05
  • 1970-01-01
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多