如何跟踪malloc和免费?

use*_*521 4 c

可能重复:
简单的C实现跟踪内存malloc/free?

我需要知道我在C程序中使用了多少内存,这里是伪代码

#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;
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我在MyFree方法中写什么(减少从usedMemory释放的内存量.

Naw*_*waz 9

您可以分配比请求更多的额外字节,并将大小存储在额外的字节中,以便您可以在MyFree函数中稍后知道大小,只需很少的计算:

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果`malloc`返回比`sizeof(int)`更大的对齐块,则返回未对齐的内存,并且允许`int`小于`size_t`.对于在特定平台上的快速入侵,只需使用任何整数类型看起来合理,当然这可能是`int`. (3认同)