【问题标题】:Why am I getting this runtime error? Line 1034: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h) [duplicate]为什么我会收到此运行时错误?第 1034 行:字符 9:运行时错误:引用绑定到类型为“int”的空指针 (stl_vector.h) [重复]
【发布时间】:2022-01-07 03:14:33
【问题描述】:

我在解决 leetcode 上的 this question 时遇到此运行时错误。

第 1034 行:字符 9:运行时错误:引用绑定到“int”类型的空指针 (stl_vector.h) 摘要:UndefinedBehaviorSanitizer:未定义行为 /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h :1043:9

这是我的代码-

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) 
    {
        int m=nums1.size();
        int n=nums2.size();
        vector<int> nums3;
        int i=0,j=0,k=0;
        while(i<m && j<n)
        {
            if(nums1[i]<=nums2[j])
                nums3[k++]=nums1[i++];
            else
                nums3[k++]=nums2[j++];
        }
        while(i<m)
            nums3[k++]=nums1[i++];
        while(j<n)
            nums3[k++]=nums2[j++];
        if(k%2==0)
            return ((nums3[k/2] + nums3[(k/2)-1])/2);
        else
            return nums3[k/2];
    }
};

【问题讨论】:

  • 在中断点,使用调试器获取堆栈跟踪。这将返回您的代码,然后您可以看到您的代码正在执行的哪些操作触发了错误。
  • 有趣的事实:当我搜索错误消息 ([c++] "reference binding to null pointer of type") 时,似乎所有的点击都是来自试图解决 Leetcode 问题的人的问题。奇怪的巧合,还是更系统的关于 Leetcode 作为资源的质量?

标签: c++ sorting runtime-error


【解决方案1】:
vector<int> nums3;

这将创建一个新的矢量对象。它完全是空的。里面什么都没有。

nums3[k++]=nums1[i++];

这会尝试通过为nums1 分配一个值来修改nums3 中某项的现有值num3 中没有值,其 size() 为 0,因此这是未定义的行为,也是您崩溃的原因。

向量的[] 运算符访问向量中的现有 值。它不会向向量添加任何内容。使用push_back()resize()ing 将向量添加到向量中。

【讨论】:

  • 好的,所以我将代码更改为nums3.push_back(nums1[i++]);,但我仍然遇到同样的错误。
  • 您是更新了仅这一行 行还是每一行?你真的明白问题是什么,我的回答有哪些不清楚的地方吗?无论如何,我只能回复问题中显示的代码,而不是未显示的修改版本。
  • 是的,我更改了直接分配 nums3[k] 的所有 4 行。我将所有这些行更改为 nums3.push_back();仍然收到错误。
  • Line 1034: Char 34: runtime error: addition of unsigned offset to 0x602000000130 overflowed to 0x60200000012c (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34 这是我现在得到的 RE
  • 这正是调试器的用途,如果您不知道如何使用它,这是学习在调试器中一次一行运行程序、监控所有变量的好机会以及它们的值,因为它们会更改并分析程序的逻辑和执行。您应该可以使用您的调试器在这个和您编写的所有未来程序中发现所有简单的问题,全部由您自己完成。了解如何有效地使用调试器是每个 C++ 开发人员的必备技能。如果没有调试器,根本不可能编写任何显着长度的代码。
猜你喜欢
  • 1970-01-01
  • 2019-11-17
  • 2022-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-03
  • 2010-09-15
  • 2021-04-30
相关资源
最近更新 更多