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(); } };
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.
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.
Explanation: free() can be called for NULL pointer, so no problem with free function call.
NULL is by definition an invalid pointer.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With