Why am I getting this runtime error? Line 1034: Char 9: runtime error: reference binding to null pointer of type 'int'


I am getting this runtime error while solving this question on leetcode.

Line 1034: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9

Here is my code-

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];
    }
};
---------------Answer---------------
vector<int> nums3;

This creates a new vector object. It is completely empty. There's nothing in it.

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

This attempts to modify the existing value of something in nums3 by assigning it a value from nums1. There are no values in num3, its size() is 0, so this is undefined behavior and the reason for your crash.

A vector's [] operator accesses an existing value in the vector. It does not add anything to the vector. Contents to a vector are added by using push_back(), or maybe by resize()ing the vector.


Previous : How to arrange list item in spinner in descending order
Next : conditonal infrastructrue changes with Terraform