In this function, a vector of integers and an integer is given as "nums" and "target"
I tried created a hash table with a key as target-nums[i] and a value as # of that keys
for example, if nums = [3, 3, 4, 5], target = 7
key -> value
| 4 -> 2
| 3 -> 1
| 2 -> 1
and code for function is,
vector<int> twoSum(vector<int>& nums, int target) {
int first=0;
int second=0;
map<int, int> HT;
vector<int> sol;
for(vector<int>::iterator i=nums.begin(); i<nums.end();i++){
if(HT[target-*i]==NULL)
HT.insert(pair<int, int>(target - *i, 1));
else
HT[target-*i]++;
}
}
However, it gives an error message of
==31==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000060 at pc 0x0000004193d5 bp 0x7ffe5e3cd950 sp 0x7ffe5e3cd948
READ of size 4 at 0x602000000060 thread T0
#2 0x7f66b38802e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)"
Under the for loop, the if condition HT[target-*i]==NULL
seems like it's never true.
I thought in CPP, if I access a non-existing key, it immediately initializes with a value NULL.
If so, that condition must be true whenever it sees a new key.
Which part am I wrong?