Need Help in Graph implementation

Please help me in correcting the below code. While running with eclipse on ubuntu, this program is crashing.


#ifndef UNDIRECTEDGRAPH_H_
#define UNDIRECTEDGRAPH_H_
#include<string>
#include<list>

class UndirectedGraph {
public:
UndirectedGraph();
virtual ~UndirectedGraph();

// returns the size of the graph (total number of node)
int getsize() const {return vertices->size();}
void addnode(std::string name);

private:
typedef struct node{
std::string name; // name of the vertex
std::list<int>* adj; // list of id's for adj vertices
node(std::string name):name(name){ adj = NULL;}
}node;

std::list<node>* vertices;
//int size;
};

#endif /* UNDIRECTEDGRAPH_H_ */


#include "UndirectedGraph.h"
#include<iostream>

using namespace std;

UndirectedGraph::UndirectedGraph() {
this->vertices = NULL;
//size = 0;
}

UndirectedGraph::~UndirectedGraph() {
// TODO Auto-generated destructor stub
}

void
UndirectedGraph::addnode(string name){
node* v = new node(name);
vertices->push_back(*v);
}

int main(){
UndirectedGraph graph;
cout<<"Graph Size:"<<graph.getsize()<<endl;
graph.addnode("delhi");
graph.addnode("bangalore");
cout<<"Graph Size later:"<<graph.getsize()<<endl;
}

You dereferenced a NULL pointer. I see nowhere in your program a way to assign vertices a new memory location (like vectices = new std::list<node>; or vertices = &FOO;).
Three other issues:
1) Why do you need a pointer to a list?
2) Your addnode function creates a memory leak. All calls to new should have following call to delete somewhere.
3) Why do you need to allocate memory in addnode? Why not just push back an rvalue object directly: vertices->push_back(node(name))
Last edited on
Thanks,
vectices = new std::list<node>; worked.
I am trying to create a graph. Graph object will just have the pointer to the list of nodes. Each node object will have list of adjacent vertices. and other node related info like name, later i plan to add weights etc.
Topic archived. No new replies allowed.