why does this c++ code run on Dev c++ but not on a website?

Viewed 1497

This code takes input of an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. We have to return the missing numbers.

Input: [4,3,2,7,8,2,3,1] Output: [5,6]

It works totally fine in Dev C++, but when i submit it a website called leetcode, it is giving me the following error

Runtime Error message:

Line 924: 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/8/../../../../include/c++/8/bits/stl_vector.h:933:9

vector<int> findDisappearedNumbers(vector<int>& nums) 
{   
  vector<int> temp;
  const int len = nums.size();
  int j=0;
  //sorted the array
  sort(nums.begin(), nums.end());
  //Added non-repetitive numbers into a temp vector
  for(int i=0;i<len;i++)
  {
    if(nums[i]!=nums[i+1])
    {
      temp[j++]=nums[i];
    }
  }
  //cleared nums vector for later use
  nums.erase(nums.begin(), nums.end());
  //added missing numbers in the sequence to both temp and nums vectors
  for(int i=0;i<len;i++)
  {
    if(temp[i]!=i+1)
    {
      temp.insert(temp.begin()+i, i+1);
      nums.insert(nums.end(),i+1);
    }
  } 
  return nums;
}

I know this code is inefficient, i have just started with c++, but can someone tell why it doesnt work on the site?

2 Answers

Your vector temp is empty when you do this:

temp[j++]=nums[i];

So you are accessing elements out of bounds. That's undefined behaviour and you cannot have any expectations on the result. Anything could happen. The compiler has no obligations any more once your code contains UB.

It only appears to work fine in Dev C++. As the error message of the other compiler says, you have Undefined Behaviors in your code. Jesper has pointer one. Another one would be the line:

if(nums[i]!=nums[i+1])

During the last iteration i is equal to len-1, so nums[i+1] tries to read num[len] which does not exist. You would need to change the loop to:

for(int i=0;i<len-1;i++)

The second loop is a little harder to fix. You are using len as limit but it is an old length of nums and you are iterating over temp. Additionally, you are modifying temp during that. What you need to do, is to check size of temp after every iteration and compare i to the current number:

for(int i=0;i<temp.size();i++)

As a side note. There are functions to clear a vector / add an element at the end. You can find the full list here.

Related