Home > Net >  Runtime error: reference binding to null pointer of type 'int' (stl_vector.h) c
Runtime error: reference binding to null pointer of type 'int' (stl_vector.h) c

Time:05-18

I know that this error refers to undefined behavior (I think), but I've reread my code 20 times and I don't see what the UB is!?

I'm doing Leetcode 238. Product of Array Except Self and here's my code (btw I don't know if this solution is right):

class Solution { public:
vector<int> productExceptSelf(vector<int>& nums) {
    vector<int> result;
    map<int, int> map;
    
    for(int i = 0; i < nums.size(); i  ){
        map[i] = nums[i];
    }
    
    for(int i = 0; i < nums.size(); i  ){
        for(auto& it : map){
            if(it.first != i){
                result[i] = nums[i] * result[i];
            }
        }
    }
    
    return result;
} };

CodePudding user response:

You can replace vector<int> result; with vector<int> result(nums.size()); This will initialize all of the values of result to 0. It won't solve the problem, but it will get rid of the runtime error you're getting.

  •  Tags:  
  • c
  • Related