-2
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

This is my code:

class Solution {

    public:
        `int removeDuplicates(vector<int>& nums) {
            vector<int>temp;
            for(int i=0;i<nums.size();i++){
               int j=0;
              ` if(temp.size()==0){
                    temp[i]=nums[i];
                }`
              `while(j<=temp.size()){
                 if(nums[i]<temp[j]){
                    j++;
                }else if(nums[i]>temp[j]){
                    temp[j]=nums[i];
                }else{
                    continue;
                }
              }`
            }
             `for(int i=0;i<temp.size();i++){
                 nums[i]=temp[i];
             }`
             int k=nums.size();
           
            return k;
        }    `
    };
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • `if (temp.size() == 0) {temp[i] = ...` This right there is an out-of-bounds access. – HolyBlackCat Aug 20 '23 at 10:49
  • Use `std::unique` instead: `nums.erase(std::unique(nums.begin(), nums.end()), nums.end());` – Ted Lyngmo Aug 20 '23 at 10:49
  • First learn C++ locally on your own system and then learn how to debug. Leetcode is about the worst place possible to learn C++ – Pepijn Kramer Aug 20 '23 at 10:49
  • Good sources to learn cpp from are : A [recent C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) or have a go at https://www.learncpp.com/ (that's pretty decent, and pretty up-to-date). For C++ reference material use : [cppreference](https://en.cppreference.com/w/). And after you learned the C++ basics from those sources, look at the [C++ coreguidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines) regularely to keep up-to-date with the latest guidelines. – Pepijn Kramer Aug 20 '23 at 11:29

1 Answers1

1

This statement

if(temp.size()==0){
     temp[i]=nums[i];
}

is guaranteed to fail when the if statement is true. If the temp vector has a size of zero then you cannot say temp[i]. The vector has a size of zero, it's does not matter what value i has temp[i] does not exist.

If you want to add an element to a vector use push_back or resize or insert. All those methods can be used to add elements to a vector, [] never adds an element to a vector.

Clearly you are just guessing at how vectors work, you guessed that if you assign to a vector it will automatically resize itself. Guessing at how C++ works rarely works out well. It's a complicated language and for beginners much of it is non-intuitive.

Consider finding a resource that will teach you C++ properly, don't expect solving leetcode puzzles to teach you much about C++.

john
  • 85,011
  • 4
  • 57
  • 81