-1

I am trying to represent a graph where

edge:

struct edge{
char a;
char b;
int weight;
}

I am trying to add my graph in this data structure:

vector<list<edge*>> graph;

In AddEdge function I get memory access violation while trying to add list in ith index of vector

void Graph::addEdge(char start, char end, int weight)
{
    int i = node_number(start); //returns index (e.g 0 if start == 'A')
    int j = node_number(end);
    Edge *s= new Edge (start, end, weight); 
    Edge* e=new Edge (end, start, weight);
    graph[i].push_back(s); //memory violation
    graph[j].push_back(e);
}

Now someone help me to add edges in my graph. Thanks!

EDIT:

I did debugging and the values of i and j are 0 and 1 respectively at the push_back() part. The debugger returns abort: memory violation the trace back is:

public:
    _NODISCARD _Ty& operator[](const size_type _Pos)
        {   // subscript mutable sequence
 #if _ITERATOR_DEBUG_LEVEL != 0
        _STL_VERIFY(_Pos < size(), "vector subscript out of range");
 #endif /* _ITERATOR_DEBUG_LEVEL != 0 */

        return (this->_Myfirst()[_Pos]);
        }
Hashir
  • 390
  • 5
  • 20
  • 2
    Pop in a `std::cout << graph.size() << ',' << i << std::endl;` to make absolutely sure `i` is in range before `graph[i].push_back(s);`. – user4581301 May 13 '20 at 20:07
  • 3
    You are assuming that's it's guaranteed that `i < graph.size()`, and you probably have a bug elsewhere that's breaking that assumption. a simple `assert(assumption)` is never lost in those cases. –  May 13 '20 at 20:08
  • 3
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/5910058) – Jesper Juhl May 13 '20 at 20:08
  • Updated the post with debugger results. I think the mistake is at the initialization of vector graph but I am not sure how to deal with vector of list. – Hashir May 13 '20 at 20:23
  • To add to the above comments, aside from fixing the problem, it is good practice to ALWAYS check you're accessing an element within its bounds. You then have the opportunity to handle the case where it is not and do something sensible (display an error message, write to a log file, etc) – castro May 13 '20 at 20:24
  • Thank you all. I fixed the error by adding two lines before pushing: int size=graph.size(); graph.resize(size + 2); – Hashir May 13 '20 at 20:26

1 Answers1

1

The problem is with the size of vector because below initialization assigns size=0

vector<list<edge*>> graph;

I have fixed the code by resizing the graph vector before pushing. Another solution would be to give initial size by

vector<list<edge*>> graph(20);
Hashir
  • 390
  • 5
  • 20