1

Trying to solve Leetcode problem #448: Find All Numbers Disappeared in an Array. The Variable nums represents a vector containing a list of numbers (including the disappeared ones).

   vector <int> temp,result;
    int max = *max_element(nums.begin(),nums.end());
    for(int i=1;i<=max;i++)
        temp.push_back(i);
        
    for(int i=0;i<int(temp.size());i++)
    {
        if(count(nums.begin(),nums.end(),temp[i])==0)
        {
            result.push_back(temp[i]);
        }
    }
    return result;

There seems to be no compile time error. But Runtime throws an error saying:

Line 811: Char 16: runtime error: reference binding to null pointer of type 'int' (stl_iterator.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_iterator.h:820:16
2
  • Are you sure nums has data in it? If not, then *max_element(nums.begin(),nums.end()) would certainly be a likely candidate for the error as you would be dereferencing a "null iterator". Commented Feb 22, 2021 at 16:40
  • There seems to be no compile time error -- All this means is that there are no syntax error. It has no bearing on whether the program is logically correct. If all that was required is to have programs compile with no errors, then there would be no bugs in C++ programs. Commented Feb 22, 2021 at 17:09

1 Answer 1

2

The input vector nums could be empty. The problem raises while calling max_element function with an empty vector. You can simple test the code by passing an empty vector (e.g., []) to the function.

The easiest solution is to check whether the input vector nums is empty in the beginning of the function. Like this:

    vector <int> temp, result;
    if(nums.size() == 0) return result;
        
    int max = *max_element(nums.begin(),nums.end());
    ...
    ...

This will solve the runtime error you are facing here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.