Ashish Paliwal
Ashish Paliwal

Reputation: 55

C++ Code: What is wrong in this?

I am writing a simple C++ program to implement graph using adjacency list. My program is below. I am using vector where each index is a vertex. Each slot in vector stores pointer to Edge_obj, Edge_obj is object of link list in adjacency list.

But when I print the first edge of graph using print_graph() I get-

0-->2087138040

I am expecting 0-->3.

What is wrong with following code?

#include<iostream>
#include<vector>
#include <forward_list>

using namespace::std;

class Edge_obj {
public:
    int V;
    Edge_obj* next;
    Edge_obj(int V, Edge_obj* next);
};

Edge_obj::Edge_obj(int V, Edge_obj* next):V(V),next(next) {}

class Graph {
public:
    int V;
    vector< Edge_obj* > VC;

    Graph(int v);
    void add_edge(int v1, int v2);
    void print_graph ();
};

Graph::Graph(int v):V(v),VC(v,nullptr) {}

void Graph::add_edge(int v1, int v2) {
    Edge_obj obj (v2, VC[v1]);
    VC[v1] = &obj;
}

void Graph::print_graph() {
    cout<<"0-->"<<VC[0]->V;
}


int main()
{
    Graph oho(4);
    oho.add_edge(0,1);
    oho.add_edge(0,2);
    oho.add_edge(0,3);
    oho.print_graph();

    return 0;

}

Upvotes: 4

Views: 246

Answers (2)

Ashish Paliwal
Ashish Paliwal

Reputation: 55

Thank you for Ron's comment above.

The problem was here:

void Graph::add_edge(int v1, int v2) {
    Edge_obj obj (v2, VC[v1]);
    VC[v1] = &obj;
}

obj is local and its scope is limited to function call. After function call finishes it will get destroyed leaving the pointer dangling.

So I improved the code by using new and memory allocation which is not scope bound.

void Graph::add_edge(int v1, int v2) {
    Edge_obj* local = new  Edge_obj(v2, VC[v1]);
    VC[v1] = local;
}

Upvotes: 1

Ron Tang
Ron Tang

Reputation: 1642

Your VC store local object pointer,this cause undefined behavior.

You could try to fix by this way:

VC[v1] = new Edge_obj(v2, VC[v1]);

or something else. Note that you should delete it after use.Or you could use smart pointer like unique_ptr for memory manage.

Upvotes: 1

Related Questions