Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory consumption in C

Tags:

c

memory

struct

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?

like image 345
ItsameMario Avatar asked Jan 30 '26 14:01

ItsameMario


1 Answers

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);
}
like image 125
Paul Praet Avatar answered Feb 01 '26 04:02

Paul Praet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!