sndp
sndp

Reputation: 9

Heap corruption alert when freing memory allocated to graph in C

MY code to destroy the graph below, when I call this function I get an alert saying heap corruption detected, picture attached. Can anyone know why it's happening?

void destroy_graph(Graph* self) {

    if (self != NULL) {
        if (self->edges != NULL) {
            for (int v = 0; v < self->V; v++) {
                EdgeNodePtr current = self->edges[v].head;
                while (current != NULL) {
                    EdgeNodePtr to_free = current;
                    current = current->next;
                    free(to_free);


                }
            }
            free(self->edges);
        }
        free(self);
    }
}

Heap corruption deteced

My code to create a graph

Graph new_graph(int vertices) {
    Graph self;

    self.V = vertices;
    self.edges = malloc(self.V * sizeof * self.edges);

        for (int v = 0; v < self.V; v++) {
            self.edges[v].head = NULL;
        }

    return self;
}

Here is the data structure:

typedef struct edge {
    int to_vertex;
    int weight;
} Edge;

typedef struct edgeNode {
    Edge edge;
    struct edgeNode *next;
} *EdgeNodePtr;

typedef struct edgeList {
    EdgeNodePtr head;
} EdgeList;

typedef struct graph {
    int V;
    EdgeList *edges;
} Graph;

Upvotes: 0

Views: 44

Answers (2)

Mark Saving
Mark Saving

Reputation: 1797

As far as I can tell, your destroy_graph function mostly looks right. But you have to be careful - you probably stack allocated the graph itself, which means you can't free it. EG the code

Graph graph = new_graph(3);
destroy_graph(&graph);

would try to free a stack-allocated graph. That's the most likely error I can see.

Upvotes: 0

hzp
hzp

Reputation: 101

Not sure what the type of edges exactly is, but in your new_graph function it should probably be:

self.edges = malloc(self.V * sizeof(self.edges[0]));

Upvotes: 1

Related Questions