1

This is how I've defined my graph. This is not a typical graph, it is specific to the type of problem I'm dealing with.

class Vertex;

class Edge
{
public:
    Vertex *org;
    Vertex *dest;
    bool dir;
};

struct Vertex{
    int id;
    vector<Edge> edges;
    int weight;
};
struct Graph{
    vector<Vertex> vertices;
};

I'm having problem in adding a vertex in the graph. This is how I'm doing it

Graph* graph1;
Vertex* first = addVertex(0);
graph1->vertices.push_back(*first);

The addVertex function is working properly, but if you still want to refer, here it is

Vertex* addVertex(int id){
    Vertex*newVertex = new Vertex;
    newVertex->id=id;
    newVertex->weight=0;
    return newVertex;
}

The function stops working just before graph1->vertices.push_back(*first);

2 Answers 2

2

graph1 itself is an unitialized pointer. So, calling it's members is causing the program to crash. Initialize it with new operator.

graph1 = new Graph();
// .......
delete graph1;

Or use a smart pointer like std::unique_ptr to automatically manage memory.

Sign up to request clarification or add additional context in comments.

2 Comments

No! Just declare Graph graph1;. Only use pointers when necessary.
@japreiss In general, yes. But here it actually depends on how graph1 grows.
0

In addition to the uninitialized Graph* graph1, there is another memory management problem in your code:

addVertex allocates a single Vertex in its own block of heap memory. But then

graph1->vertices.push_back(*first);

copies first into the block of memory managed by graph1's std::vector.

I guess that you are new to C++ coming from another language like Java or Python. You should read an introductory C++ book. Memory management in C++ has a lot of pitfalls and concepts to keep track of compared to other languages.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.