Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference binding to null pointer of type 'value_type'

Tags:

c++

vector

This is leetcode 26. Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length. An example is given nums = [1,1,2], the function should return [1,2].

Below is my code. I delete all the other duplicates, just leave one of them. However I always got an error of reference binding to null pointer of type 'value_type' when submitting. I would appreciate if anyone can help me with this!

class Solution { public:     int removeDuplicates(vector<int>& nums) {         int i = 0;         while(i < nums.size() - 1) {             if (nums[i] == nums[i + 1]) {                 nums.erase(nums.begin() + i);             }              else i++;         }         return nums.size();     } }; 
like image 545
uvzoeeeey Avatar asked Dec 22 '17 22:12

uvzoeeeey


People also ask

What happens when you reference a null pointer?

A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. NULL pointer dereference issues can occur through a number of flaws, including race conditions, and simple programming omissions.

What is the type of null pointer?

A null pointer constant is an integer constant expression that evaluates to zero. For example, a null pointer constant can be 0, 0L , or such an expression that can be cast to type (void *)0 . You can specify any of the following values for a null pointer constant: 0.

Can free applied to null pointer?

Explanation: free() can be called for NULL pointer, so no problem with free function call.

IS null pointer a valid pointer?

NULL is by definition an invalid pointer.


1 Answers

vector<T>::size() returns a value of type size_t, which is an unsigned type. Let's say the vector passed in is empty and therefore the vector's length is 0. nums.size() - 1 will cause integer underflow and you will actually be comparing 0 with a very large positive number. This will evaluate to true causing the loop to run and i going pass the array bounds.

To fix this you can cast nums.size() to int preemptively or store the size in an integer variable and compare with that.

like image 56
David G Avatar answered Sep 28 '22 00:09

David G