I have two simple classes representing nodes and edges in a connected graph structure.
//node.h
#include "edge.h"
#include <string>
#include <list>
#include <utility>
using namespace std;
class Edge;
class Node {
private:
list<Edge> edgeList;
string nodeName;
pair <int, int> coordinates;
public:
Node();
void setXY(int x, int y);
void insertEdge(Edge& edgeToAdd);
void removeEdge(Edge& edgeToAdd);
list<Edge> getEdgeList();
};
With insertEdge
method implemented in node.cpp as:
void Node::insertEdge(Edge& edgeToAdd) {
this->edgeList.push_back(edgeToAdd);
}
The Edge
class is another simple class declared in edge.h:
#pragma once
#include "node.h"
class Node;
class Edge {
private:
Node* destinationNode;
int edgeWeight;
public:
//constructor
Edge(Node* destNode, int w);
//Setters and Getters
void setDestinationNode(Node* destNode);
void setEdgeWeight(int weight);
Node* getDestinationNode();
int getEdgeWeight();
};
In another file in which I am writing unit tests I try to insert a pointer to an edge object using the insertEdge
method detailed above:
SECTION("an edge gets inserted to the adjacency list")
{
Node* b = &Node();
Edge* e = new Edge(b,1);
b->insertEdge(*e);
list<Edge> edgelist = b->getEdgeList();
}
I have determined that edgeList.push_back(edgeToAdd)
results in a segmentation fault due to illegal memory access. Stepping through the code I can see that the variables which are being illegally accessed are _Prev
and _Next
which are members of the allocator of the std::list. I suspect that my problem has something to do with how I have declared std::list<Edge*> edgeList
My question is, what is a correct way to add a pointer to a std::list which has only being declared?