Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track malloc and free? [duplicate]

Tags:

c

Possible Duplicate:
Simple C implementation to track memory malloc/free?

I need to know how much memory I have used till now in a C program and here is the pseudo code

#include <stdio.h>

int usedMemory =0;

void *MyMalloc(int size){
 usedMemory = usedMemory +size ;
 return malloc(size);
}

void MyFree(void *pointer){
/*****************what should i write here????*************/
}
int main(int argc, char *argv[])
{
    char *temp1= (char *)MyMalloc(100);
    char *temp2= (char *)MyMalloc(100);

    /*......other operations.........*/

    MyFree(temp1);
    MyFree(temp2);

    return 0;
}

Can anyone tell me what to write in the MyFree method(which decrements the amount of memory freed from usedMemory.

like image 891
user650521 Avatar asked Dec 13 '22 07:12

user650521


1 Answers

You could allocate few extra bytes more than asked, and store the size in the extra bytes, so that you could know the size later on, in MyFree function, with little calculation as:

unsigned long int usedMemory = 0;

void *MyMalloc(int size)
{
  char *buffer = (char *) malloc(size + sizeof(int)); //allocate sizeof(int) extra bytes 
  if ( buffer == NULL) 
      return NULL; // no memory! 

  usedMemory += size ;      
  int *sizeBox = (int*)buffer;
  *sizeBox = size; //store the size in first sizeof(int) bytes!
  return buffer + sizeof(int); //return buffer after sizeof(int) bytes!
}

void MyFree(void *pointer)
{
   if (pointer == NULL)
       return; //no free

   char *buffer = (char*)pointer - sizeof(int); //get the start of the buffer
   int *sizeBox = (int*)buffer;
   usedMemory -= *sizeBox;
   free(buffer);
}
like image 53
Nawaz Avatar answered Dec 14 '22 21:12

Nawaz