I am creating a simple graph with nodes and edges. I got the functionality going but got some memory bugs.
I have a typedef struct in header file:
typedef struct Graph_s* Graph;
And implementation in c. file:
struct Graph_s {
Node* nodeArray;
Edge* edgeArray;
size_t edges;
size_t nodes;
};
And function for construction:
Graph create_graph() {
Graph newGraph = malloc(sizeof(Graph));
newGraph->edges = 0;
newGraph->nodes = 0;
return newGraph;
}
The line Graph newGraph = malloc(sizeof(Graph)) gives: Invalid write of size 8 from Valgrind.
malloc(sizeof(Graph))is only allocating enough memory for a pointer. Change it tomalloc(sizeof(struct Graph_s)).