简体   繁体   中英

C++ Deallocating memory giving me aborted dump?

I have a deconstructor that is suppose to deallocate the pointers I made but it's not working as it should. Heres part of my class that declares all the pointers

private:
    struct Edge {
        Vertex* node;
    };

    struct Vertex {
        vector< Edge > adjList;
        Vertex *path;

    };

    vector<Vertex*> vertices;
    priority_queue< Vertex* > pq;

And occasionally I declare new vertexs in functions like so Vertex* v = new Vertex . I've been told that I do not have to worry about deleting these pointers. Heres my function that deallocates my memory that is called by my deconstructor

void makeEmpty( ) {
    for(int i = 0; i < total; ++i)
        makeEmpty( vertices[ i ] );
    total = 0;
}

void makeEmpty( Vertex * & v ) {
    for( int i = 0; i < v->adjList.size(); ++i ){
        //delete v->adjList[ i ].node;
        //v->adjList[ i ].node = nullptr;
    }
    if ( v->path != nullptr ) {
        makeEmpty( v->path);
        delete v;
        v = nullptr;
    }
}

I commented out my adjList because I was experimenting with different ways on how to make this worked but nothing is. Can anyone help me?

Forgot to mention that all of these pointers are related to the same vertex/node. All of the vertex/nodes that are used is inside my vertices

Edit: I got it to worked, turns out I was overcomplicating things and just needed to do this

void makeEmpty( Vertex * & v ) {
        delete v;
        v = nullptr;
}

" Vertex* v = new Vertex I've been told that I do not have to worry about deleting these pointers."

Well, they're raw pointers. You do have to worry about deleting them. But often the easiest solution is to put all your vertices in a Graph class, let that own everything, and don't worry about ownership at node level.

Things get a bit hairy if you are cutting graphs in two, or are doing operations which might cut a graph in two. But even then, it's usually not too hard to have an operation which extracts a new Graph from the old Graph , and transfer the affected nodes to the new Graph.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM