PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, June 26, 2022

[FIXED] Why getting reference binding to null-pointer error?

 June 26, 2022     c++, error-handling, graph, runtime-error, vector     No comments   

Issue

I am solving the following Leetcode problem:

https://leetcode.com/problems/find-if-path-exists-in-graph/

I am getting the following error:

Line 1034: Char 9: runtime error: reference binding to null pointer of type 'std::vector<int, std::allocator<int>>' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9

The code for my approach:

class Solution {
public:
    void dfs(int *visited,int node,vector<vector<int>>&adj)
    {
        visited[node]=1;
        for(auto child:adj[node])
        {
            if(visited[child]==-1)
                dfs(visited,child,adj);
        }
    }
    bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
        vector<vector<int>>adj;
        for(auto it:edges)
        {
            adj[it[0]].push_back(it[1]);
            
        }
        int visited[n];
        for(int i=0;i<n;i++)
            visited[i]=-1;
        
        dfs(visited,source,adj);
        
        return visited[destination]==1;
    }
};

I'm getting this error for almost every graph problem. Can someone point out the mistake?


Solution

The outer vector of adj should be resized, before adding elements to the inner vector.

bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
    vector<vector<int>>adj;
    for(auto& it:edges)
    {
        if (adj.size() < (it[0] + 1))
        {
            adj.resize(it[0] + 1);    
        }
        
        adj[it[0]].push_back(it[1]);
            
    }
    
    //Rest of the code  
}


Answered By - ruvenij
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing