0
Error trying printing a graph C++.
I'm trying to print a graph with a toString() function, where basically the graph is a vector<Edge *>. My idea is to iterate in each element and print its element as a string. But is not working... Here is the code. https://code.sololearn.com/cH3RyaoSp3yM The error I'm getting is this: terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped) And using a sanitize, it points to the lines 84 and 106. I have the feeling that maybe I can solve it if I allocate memory dynamically, but in this point I'm not sure if that is the solution (and what element I should allocate). I don't know what to do to solve the problem.
2 odpowiedzi
+ 2
As far as I can see the problem is in insertEdge where you are creating the nodes and edges on the stack and then add them to a vector. Upon leaving the function the objects are destroyed but they are still in the vector.
You'll have to allocate memory dynamically there.
+ 2
Dennis that's the answer, sometimes I have some difficulty to know when allocate memory dynamically, this is the case where I should do that and I did.
After that it works perfectly (of course, deleting that memory after doing that).
Now I understand, when I was debugging , why the objects were destroyed but they still in the vector. Thx! :)