it's my first question here so I apologize for eventual formal mistakes you may found in my post.
I'm coding a simple class for "Undirected Connected Weighted Graphs", which must use Adjacency Lists based on vectors.
The issue is that when I run the program from Eclipse, MS Windows says it "stops working" and after debugging I get an "Unhandled exception at 0x00AE251A .... Access violation writing location..." message.
Looking around I found that this issue may be caused by a missing pointer destruction or pointer initialization (?). I switched from the standard pointer to the shared_ptr to troubleshoot this issue but the error is the same...
Can anybody enlighten me on this? I lost almost a whole day trying to find the cause without success.
class UndirectedGraph
{
private:
int V;
std::vector<std::shared_ptr<std::pair<int,int>>>* adj;
public:
UndirectedGraph(int V)
{
this->V = V;
this->adj = new std::vector<std::shared_ptr<std::pair<int,int>>>;
}
void addEdge(int v, int w, int weight)
{
auto sp = std::make_shared<std::pair<int,int>>(std::make_pair(v,weight));
adj[v].push_back(sp);
}
int main()
{
UndirectedGraph G1(7);//Ok
G1.addEdge(0,1,9);//Ok
G1.addEdge(1,2,5);//Ok
G1.addEdge(2,0,8);//EXCEPTION RAISED HERE (if line is commented all run fine)
return 0;
}
I noticed a couple of errors in the code:
If what you need are adjacency lists, then this->adj should be a vector of vectors. Currently, its just a 1-D vector of <int,int> pairs. Instead it should be:
std::vector<std::vector<std::shared_ptr<std::pair<int,int>>>>* adj;
In the constructor, this->adj should be initialized as follows:
this->adj = new std::vector<std::vector<std::shared_ptr<std::pair<int,int>>>>(V);
Now, in the addEdge function, you need to first access the vector corresponding to node 'v' and then, into that vector, you need to push the pair (w, weight) [NOTE that, even if we ignore the error that there's only vector, the logic is still incorrect since you're pushing (v, weight) instead of (w, weight) into that vector]. The modified addEdge function would be something like this:
void addEdge(int v, int w, int weight)
{
auto adjacencyList = adj->at(v);
auto sp = std::make_shared<std::pair<int,int>>(std::make_pair(w,weight));
adjacencyList.push_back(sp);
}
Hope this helps you
Related
Currently I'm just starting off with creating nodes for my tree. The idea I had in mind was to simply create something like this:
class Node
{
private:
int key_;
std::vector< Node * > child_;
public:
Node(int key)
: key_(key), child_()
{
}
Node * get_child(int key) const
{
return child_[key];
}
};
Nothing too fancy, right?
Inside the main, I call all the header files and have initialized the whole entire thing like this
Node child(0);
What causes some frustration right now is when I try to simply just check if everything in my node is truly initialized. All I'm doing in the main is this.
std::cout << node.get_child(0) << std::endl;
The dreaded segmentation fault error comes up which means that the memory allocation of the vector is off. My question is this, if this is actually what's happening, what in my code is wrong so far? If it is not, please clarify on what exactly in my class template is wrong.
In the constructor for Node, you set the internal key value, and construct an empty vector. You don't have any code shown that adds anything to the vector, and trying to access element 0 of an empty vector results in Undefined Behavior (a crash, in your case).
You probably want something like child(1) (to create one node in the vector), child(key + 1, nullptr) (to create null node pointers so that elements in the 0..k inclusive range are valid) or a loop in the constructor to set actual nodes into the vector.
I am trying to use the C++ "Clipper Library" (http://www.angusj.com/delphi/clipper.php), but when I try to return one of the objects from the clipper library from a function, it seems to become null or is altered somehow
Here is the function I wrote. The only relevant lines should be the last 3.
ClipperLib::PolyTree MeshHandler::trianglesToPolyTreeUnion(std::vector<Triangle> triangles)
{
// Make all of the triangles CW
for (auto& triangle : triangles)
{
triangle.makeClockwise();
}
// Set up the Clipper
ClipperLib::Clipper clipper;
// To take a union, add all the paths as "subject" paths
for (auto& triangle : triangles)
{
ClipperLib::Path triContour(3);
triContour[0] = convertGLMToClipperPoint(triangle.getVertex(0));
triContour[1] = convertGLMToClipperPoint(triangle.getVertex(1));
triContour[2] = convertGLMToClipperPoint(triangle.getVertex(2));
clipper.AddPath(triContour, ClipperLib::PolyType::ptSubject, true);
}
// Now get the PolyTree representing the contours
ClipperLib::PolyTree tree;
clipper.Execute(ClipperLib::ClipType::ctUnion, tree);
return tree;
}
When I call clipper.execute, it writes into the tree structure some contour information. It writes the correct information, and I've tested that it's correct. However, when I return the tree, it doesn't seem to copy anything, and the PolyTree that results from this function is empty.
I'm sure that there's nothing wrong with the library and that I'm just making a beginner c++ mistake here. Hopefully someone has an idea of what it might be.
Thanks!
edit: For reference, here is a documentation page for the polytree (http://www.angusj.com/delphi/clipper/documentation/Docs/Units/ClipperLib/Classes/PolyTree/_Body.htm)
edit: I thought the clipper library wasn't open source, but it is. Here is the code
typedef std::vector< IntPoint > Path;
typedef std::vector< Path > Paths;
class PolyNode;
typedef std::vector< PolyNode* > PolyNodes;
class PolyNode
{
public:
PolyNode();
Path Contour;
PolyNodes Childs;
PolyNode* Parent;
PolyNode* GetNext() const;
bool IsHole() const;
bool IsOpen() const;
int ChildCount() const;
private:
unsigned Index; //node index in Parent.Childs
bool m_IsOpen;
JoinType m_jointype;
EndType m_endtype;
PolyNode* GetNextSiblingUp() const;
void AddChild(PolyNode& child);
friend class Clipper; //to access Index
friend class ClipperOffset;
};
class PolyTree: public PolyNode
{
public:
~PolyTree(){Clear();};
PolyNode* GetFirst() const;
void Clear();
int Total() const;
private:
PolyNodes AllNodes;
friend class Clipper; //to access AllNodes
};
Before doing anything, make sure the following program works correctly:
int main()
{
PolyTree p1;
// fill PolyTree with some values that make sense (please add code to do this)
//...
PolyTree p2 = p1;
PolyTree p3;
p3 = p1;
}
That is basically what we want to test. If you can get this code to work (add the relevant headers and initializations necessary), then you can focus back on the function. If the code above doesn't work, then there is your answer.
You need to get the code above to produce the correct copy semantics, and even just important, when main() exits, no memory corruption occurs on the destruction of p1, p2, and p3.
So either you can fix the class to copy safely, or forget about it and live with a class that you have to handle very carefully and in limited situations (i.e. you can't reliably return copies of it as you're doing now).
For the record and combining all the responses in the lengthy discussion to the question.
Problems are:
The value returned is a local variable that goes out of scope. This invokes the PolyTree destructor
The PolyTree contains a vector of PolyNode * pointers. Those are allocated when clipper.Execute() is invoked.
However PolyTree::Clear() does delete the nodes... and Clear() is invoked by the destructor.
So within the function, the content is correct (allocated by Execute()), when passed outside, in the absence of copy constructors and operator=, the destructor of the local variable is invoked an the nodes are cleared, the result received outside of the function is empty.
The code for PolyTree::Clear()
void PolyTree::Clear()
{
for (PolyNodes::size_type i = 0; i < AllNodes.size(); ++i)
delete AllNodes[i];
AllNodes.resize(0);
Childs.resize(0);
}
Probably you should follow the pattern of Execute and define your function as:
void MeshHandler::trianglesToPolyTreeUnion(std::vector<Triangle> triangles,ClipperLib::PolyTree &tree)
Assuming you don't want to modify the (obviously badly designed) Clipper library, you can do it like I suggested in my comment:
// Make sure to have this at the top of your header file:
#include <memory>
std::unique_ptr<ClipperLib::PolyTree> MeshHandler::trianglesToPolyTreeUnion(std::vector<Triangle> triangles)
{
// Rest of your code...
std::unique_ptr<ClipperLib::PolyTree> tree(new ClipperLib::PolyTree);
clipper.Execute(ClipperLib::ClipType::ctUnion, *tree);
return tree;
}
Then, when calling your function:
std::unique_ptr<ClipperLib::PolyTree> tree(yourMeshHandler.trianglesToPolyTreeUnion(/*...*/);
// make use of tree...
Still, I would suggest opening a ticket (if there's a bug tracker) or contacting the library's author about this issue.
Is there already a solution for this problem? I am dealing with the same problem.
Still no luck. The polytree outputs only memory adres.
when using : qDebug()<< "child id " << polynode->Childs;
When we have 2 childs, the output in terminal is :
std::vector(0x55f30d2a91b0, 0x55f30d258480)
I hope someone knows how to solve this..
Your problem is in the third line from the bottom of trianglesToPolyTreeUnion. The tree you are creating is created on the stack and is only in scope within the function.
You should dynamically allocate the memory and return a pointer to the tree or make your tree object a class member so it is still within scope once the function returns.
Working on adjacency list --> directed weighted graph
One class looks like this, i.e. header:
class CGraph;
class CMap {
public:
//voided constructors and destructors
//functions one is:
void SetDirGraph(string commands);
private:
CGraph* m_myMap;
};
Second class:
class CNode {
public:
//voided constructor and desctructor
int m_distance, m_vert;
bool m_isKnown;
};
typedef struct edges {
int v2, weight;
} edge;
class CGraph {
public:
CGraph(int map_size);
~CGraph(void);
void AddMap(int v1, int v2, int weight);
void AddEndVert(int v2, int weight);
private:
list<edge> List;
int size;
public:
CNode* verts;
};
I'm reading vertices from a file, and that works. My problem is I am having trouble creating an adjacency list based on the code given. I'm trying to use pointers first that points to a list and it is not working correctly. I don't know how to create my pointers to the list without writing over them.
void CMap::SetDirGraph(string command) {
istringstream buffer(command)
char ch;
int num, vert1, vert2, weight; //specify vertices and weight and number of vertices
buffer>>ch; //throw away first character (not needed)
buffer>>num // size of vertices
while(!buffer.eof()) { // keep reading until end of line
buffer>>v1; // vertex start
buffer>>v2; // vertex end
buffer>>weight;
m_myMap = new CGraph(map_size); //initialize m_myMap.
m_myMap->verts->m_vert = v1; // mymap->verts->vert points to first edge
m_myMap->AddMap(v1, v2, weight); // create list?
m_myMap->AddEndVert(v2, weight); //create list? push v2 and weight on my list using my list.
}
}
I've tried several different ways and I keep confusing myself, any point in the right direction would be awesome.
EDIT:
I have more code too if needed to be produced, just publishing the main stuff.
What I mean by "not working" is that I am just writing over the previous vertex. I don't know if I should create an array using m_myMap (tried and still writes over and get a memory error as well). No compiler errors.
I don't know how to create my pointers to the list without writing over them.
Apart from your application, the answer to this question is the new operator, which I assume you are aware of, since you used it within your example code. Code like int * a = new int(42); allocates memory for an int on the heap and you are responsible for cleaning it up when it is not needed anymore. You thereby have full control over how long a variable will be available. In int x = 42; int * a = &x; on the other hand, x will automatically be cleaned up when it runs out of scope, and a will be a pointer to a memory block that has no meaningful data in it anymore. If you try to dereference it, you will encounter undefined behavior, and, if you are lucky, your program will blow up.
If you can use the C++11 standard, or a library that offers smart pointers, you should prefer those over managing the pointer yourself whenever possible. A smart pointer is an object that holds the allocated memory and frees it automatically when it is destructed. More specific information depends heavily on which sort of smart pointer you are using. The reason for using smart pointers is that doing the management yourself is tedious and error prone. If you do not delete your pointers you had allocated, your application will keep on allocating more memory until it blows up some day (depending on how often and how much memory you allocate); this is called leaking. If you call delete more than once, your program will bail out as well. Here is an example of C++11 shared_ptr in your application:
class CMap
{
private:
std::shared_ptr<CGraph> m_myMap;
// etc.
};
// in SetDirGraph
m_myMap.reset( // if the smart pointer has previously been managing
// memory, it will free it before allocating new
new CGraph(map_size) // allocate CGraph as before
);
Besides that, what hopefully answers your question, I have run into several potential problems concerning your code:
Definitely wrong:
In SetDirGraph you set m_myMap->verts->m_vert = v1. m_myMap->verts is a pointer. You have freshly created m_myMap and thus verts is not initialized, hence pointing at a random block of memory. You then try to dereference it by m_myMap->verts->m_vert = v1. This cannot work. You need to create verts first, i.e. verts = new CNode;.
typedef struct edges { /* etc */ } edge; is a C construct and there is no need for the typedef wrapper in C++. It does work and all, but it is really redundant and lots of those constructs just pollute the namespace you are working in.
Do you really need pointers in the first place? Your provided snippets do not hint at why you would need to use them. You will want to reduce usage of pointers to a minimum (or at least use smart pointers, see above)
I'm trying to implement the Ford Fulkerson Algorithm in C++.
However, I'm having trouble with my find_edge function. When I call this function in my_alg, it chooses the correct edge and then the flow is incremented in my_alg. It chooses the right edge and increment its flow (flow), but when I call the find_edge function again, the flow is not incremented as it should be.
This results in an endless loop of my algorithm. Probably I do something wrong with the pointers. You can see my code below.
//An object of this class represents an edge in the graph.
class Edge
{
private:
//Node *prev;
public:
int flow;
Edge(Node *firstNode, Node *secNode, unsigned inCost) {
orgNode = firstNode;
dstNode = secNode;
bridge_capacity = inCost;
}
Edge() {
flow=0;
}
};
//An object of this class holds a vertex of the graph
class Node
{
public:
Node *prev;
vector<Edge>& getAdjNodeList() {
return adjNodeList;
}
};
Edge *find_edge(Graph *g,Node *from,Node *to) {
vector<Edge> b=from->getAdjNodeList();
for(int i=0;i<b.size();i++) {
if(b[i].getDstNode()==to)
return (&b[i]);
}
return NULL;
}
int my_alg(Graph *as,Node *source,Node *sink){
Edge *find_edge();
int max_flow=0;
while(bfs(as,source,sink)) {
Node *b=as->nodeList[num_isl];
int inc=100000000;
while(b->prev!=NULL) {
Edge *bok=find_edge(as,b->prev,b);
inc=min(inc,bok->get_bridge_capacity()-bok->flow);
b=b->prev;
}
b=as->nodeList[num_isl];
while(b->prev!=NULL){
Edge *bok = find_edge(as,b->prev,b);
bok->flow += inc; // This is the place the flow is incremented
bout << bok->flow; // Here, everything is alright.
bok = find_edge(as,b->prev,b);
cout << bok->flow; // However, this is is not the correct result.
}
max_flow+=inc;
}
return max_flow;
}
I had a more thorough look at your code. To help you track your problems down yourself in the future, I will show you a sample process of finding the error.
If you really can not find the problem by looking at the code, you may want to strip down everything that obfuscates your view on the problem. The reduced code could look like this:
class Edge {
public:
int flow;
};
class Node {
private:
vector<Edge> adjNodeList; // list of outgoing edges for this vertex
public:
vector<Edge> & getAdjNodeList() {
return adjNodeList;
}
void addAdjNode(Node* newAdj) {
adjNodeList.push_back(Edge(newAdj));
}
};
int main() {
Node *node1 = new Node();
Node *node2 = new Node();
node1->addAdjNode(node2);
vector<Edge> t = node1->getAdjNodeList();
vector<Edge> f = node1->getAdjNodeList();
t[0].flow = 11;
cout << t[0] << endl;
cout << f[0] << endl;
}
If you would run this code, you would notice that t[0] and f[0] are not the same. As I just copied the crucial elements of your code, the reason should still be the same.
What is happening here? When calling
vector<Edge> t = node1->getAdjNodeList();
the adjacency list is returned by reference, which should leave you with a reference to the original list - you should be able to change it's elements, shouldn't you? However, when assigning this reference to the newly allocated vector t, the implicit copy constructor is called, thus t will contain a copy (!) of your vector while you wanted to save a reference.
To get around this problem, you could just have done the following:
vector<Edge> & t = node1->getAdjNodeList();
which saves the reference and does not create a new object.
I can only assume why the pointers happened to be identical between calls to the function: The object probably was copied to the same place every time. Furthermore, note that you increased the value of an object that did not exist anymore - the copy was deleted with the end of the find_edge-call.
It took some time to give an answer to your question as you did not track the problem down yourself. If you had given the example above, I bet your solution would have been there within a matter of minutes. You are encouraged to raise your problems here at stack overflow - however, most members will not be willing to work through a lot of code to identify the problem themselves. That means, high quality answers usually require questions that directly come to the point. (The last paragraph was intended to help you in the future, however, it could be reduced without altering the question).
Apart from that, I would strongly encourage you not to use your objects the way you do. By passing everything as references and making all changes outside the object, you essentially bypass the encapsulation that makes object orientated programming that powerful. For example, it would be much wiser (and would not have given you your problem) if you just had added another function increaseFlow(Edge* to, int increment) to your Node and had done everything within the object.
Hope I could help.
I have narrowed down the problem to this line:
indg = nets[i]->adjlist[i].size(); // indg is in a method of the Ensemble class
Where the above variables are
vector<DDNetwork*> nets; // this vector is in the Ensemble class
int indg;
class DDNetwork
{
friend class Ensemble;
...
public:
vector< vector<int> > adjlist; // the adjacency list of the network
...
};
I don't understand why indg = nets[i]->adjlist[i].size(); would cause a segfault, is there something I am missing? Also if you need more information I can add it.
EDIT: I just realized what was wrong, I am using the same index for adjlist that I am for nets, the line
indg = nets[i]->adjlist[i].size();
should be:
indg = nets[i]->adjlist[j].size();
EDIT: After stepping through the debugger, I noticed that in the constructor of Ensemble, nets.size() = 10 (expected), but when the method Ensemble::alloc_dev_memory is called, nets.size() = 803384 (unexpected), so I think that JaredPar's second suggestion might explain the problem. Here is the code that adds DDNetwork* instances into the nets variable:
Ensemble::Ensemble(int N, float K, int S, bool seedrand, int ltype, int numNets)
{
this->N = N;
this->K = K;
this->S = S;
this->ltype = ltype;
this->numNets = numNets;
if(seedrand)
srand(time(0));
nets.resize(numNets); // make a vector of pointers to DDNetwork
for(int i=0; i < numNets; ++i)
nets[i] = new DDNetwork(N,K,S,seedrand,ltype);
// pre-compute the S^k for k=0,1,...,Kmax
Spow[0]=1; // S^0 = 1
int k=1;
while(k <= Kmax*2) {
Spow[k] = S*Spow[k-1]; // S^k = S*(S^(k-1))
++k;
}
}
This constructor is called when I instantiate the ensemble variable in my main function:
// instantiate ensemble of networks
Ensemble ens(N, K, S, seed_rand, multiedge, numNets);
// run_the ensemble one time step
ens.run_gpu();
And after that, Ensemble::run_gpu calls Ensemble::alloc_dev_memory, then when nets[i]->adjlist[j].size() is called, that's when I receive the segmentation fault.
How would the nets reference get uninitialized?
The problem is likely one of the following
The DDNetwork* reference in nets[i] is uninitialized causing a segfault when you access the members.
The size of nets and each instance of adjlist is not kept in sync causing one of the offsets to be invalid
Could you post the code which adds DDNetwork* instances into the nets variable?
There are two possibilities. Either there isn't a new DDNetwork at index nets[i] or adjlist[i] hasn't been created.
To have a square vector of vectors you need to resize them properly:
adjlist.resize( MAX );
for (int i = 0; i < MAX; ++i)
adjlist[i].resize( MAX );
...only then can you index them. Alternatively you can push_back proper values.
Note also that you use the same index for the nets array, and the adjlist array, unsure whether that was intended.
I found the source of the segfault by accident, I was doing some crude debugging because GDB didn't have information about my main.cpp file, and in order to print out nets.size(), I had to temporarily make vector<DDNetwork*> nets public, after doing that, I realized that the program didn't segfault anymore. I thought it might have to do with the private/public distinction, but when I moved the line
public:
vector<DDNetwork*> nets;
private:
to
public:
private:
vector<DDNetwork*> nets;
line, the program still didn't segfault, so I tried moving the line vector<DDNetwork*> nets; back to where it used to be, all the way below all of the other method and member declarations, just before the closing brace };, and the program began to segfault as before. What is it about the location of the line vector<DDNetwork*> nets; that was causing the segfault?