I would like to know how to measure the memory consumption of a graph in C. With the following Code I initialize a Graph with V nodes and no Edges:
Graph GRAPHinit(int V)
{
int v;
Graph G = malloc(sizeof *G);
G->V = V; G->E = 0;
G->adj = malloc(V*sizeof(link));
for (v = 0; v < V; v++) G->adj[v] = NULL;
return G;
}
The Graph is a struct, represented as a adjacency list:
struct graph {
int V;
int E;
link *adj;
};
typedef struct node *link;
struct node {
int v;
link next;
};
typedef struct graph *Graph
Is it possible to measure the amount of space G uses with the sizeof-Operator? Other possibilities?
No, you cannot do it purely with the sizeof-operator as this can only be used for compile-time, static memory allocations.
At best you can implement a new function like
unsigned int getMemoryUsage(Graph *g){
return sizeof(*G) + G->V * sizeof(link);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With