简体   繁体   中英

memory usage of a particular function in c program

I am doing a project of Data Structures in c language in which I have been using some functions like insertion in a tree, deletion from a tree, finding a particular value in a tree. I have to calculate memory using of every individual function like memory usage in insertion function, deletion function etc Kindly guide me if there is any library or built-in function to calculate memory usage. I have found some content like to find memory usage of whole program but I am concerned with memory usage of a particular function.

Your question is vague, but I will try to answer it like I understand it. Allocated memory for a tree with lets say 20 Nodes will consume 20xNode size so lets say our Node looks like this:

typedef struct node 
{
    int val;
    struct node * next;
} node_t;

Let's assume you have a 64 bit system, then an integer will take 4 bytes and a pointer would take another 8 bytes. Together Node size will be 12 bytes of allocated memory ready to use. For our example a tree with 20 nodes will consume 240 bytes of memory. When you add Nodes to the tree you are basically increasing the memory stored and hence expanding the memory usage. If you need to keep check of how much memory is used by each function you should calculate each function usage separately(remember that each function stores the variables locally and not globaby) and add the overall allocated or freed memory in the process. Let's say a function that adds a node looks like this :

void addNode(node_t *leaf, int a)
{
  node *new=malloc(sizeof(node));
  new->val=a;
  new->next=NULL;
  *leaf->next=new;
}

this function will add 12 bytes to your overall memory usage. you can add a counter in your main function to keep track of the memory stored and at the end of an addition add sizeof(node) to the counter via pointers or subtracts from it.

If i understand your question you don't need to keep track of local memory because its not important after the functions end. You just need to keep track of memory added or subtracted after initial allocation for the tree you receive.

To my knowledge there are no function that can do it for you so you will have to add it yourself. My suggestion to you is to break your program to many little function and at the end of each keep track of what it has done to the overall memory stored. you can also keep track of local variables but they are deleted at each transition between function (if they are not allocated pointers).

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