简单的C实现跟踪内存malloc/free?

dub*_*nde 11 c dynamic-memory-allocation

编程语言:C平台:ARM编译器:ADS 1.2

我需要跟踪melloc/free项目中的简单调用.我只需要了解程序分配了所有资源后需要多少堆内存的基本概念.因此,我为malloc/free调用提供了一个包装器.在这些包装器中,我需要在malloc调用时递增当前内存计数,并在free调用时递减它.这个malloc案例很简单,因为我有来自调用者的大小.我想知道如何处理这种free情况,因为我需要在某处存储指针/大小映射.这是C,我没有标准的地图来轻松实现这一点.

我试图避免在任何库中链接,所以更喜欢*.c/h实现.

所以我想知道是否已经有一个简单的实现可能会引导我.如果没有,这是继续实施的动机.

编辑:纯粹用于调试,此代码不随产品提供.

编辑:根据Makis的回答进行初步实施.我很感激对此的反馈.

编辑:重新实施

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <limits.h>

static size_t gnCurrentMemory = 0;
static size_t gnPeakMemory    = 0;

void *MemAlloc (size_t nSize)
{
  void *pMem = malloc(sizeof(size_t) + nSize);

  if (pMem)
  {
    size_t *pSize = (size_t *)pMem;

    memcpy(pSize, &nSize, sizeof(nSize));

    gnCurrentMemory += nSize;

    if (gnCurrentMemory > gnPeakMemory)
    {
      gnPeakMemory = gnCurrentMemory;
    }

    printf("PMemAlloc (%#X) - Size (%d), Current (%d), Peak (%d)\n",
           pSize + 1, nSize, gnCurrentMemory, gnPeakMemory);

    return(pSize + 1);
  }

  return NULL;
}

void  MemFree (void *pMem)
{
  if(pMem)
  {
    size_t *pSize = (size_t *)pMem;

    // Get the size
    --pSize;

    assert(gnCurrentMemory >= *pSize);

    printf("PMemFree (%#X) - Size (%d), Current (%d), Peak (%d)\n",
           pMem,  *pSize, gnCurrentMemory, gnPeakMemory);

    gnCurrentMemory -= *pSize;

    free(pSize);
  }
}

#define BUFFERSIZE (1024*1024)

typedef struct
{
  bool flag;
  int buffer[BUFFERSIZE];
  bool bools[BUFFERSIZE];
} sample_buffer;

typedef struct
{
  unsigned int whichbuffer;
  char ch;
} buffer_info;


int main(void)
{
  unsigned int i;
  buffer_info *bufferinfo;

  sample_buffer  *mybuffer;

  char *pCh;

  printf("Tesint MemAlloc - MemFree\n");

  mybuffer = (sample_buffer *) MemAlloc(sizeof(sample_buffer));

  if (mybuffer == NULL)
  {
    printf("ERROR ALLOCATING mybuffer\n");

    return EXIT_FAILURE;
  }

  bufferinfo = (buffer_info *) MemAlloc(sizeof(buffer_info));

  if (bufferinfo == NULL)
  {
    printf("ERROR ALLOCATING bufferinfo\n");

    MemFree(mybuffer);

    return EXIT_FAILURE;
  }

  pCh = (char *)MemAlloc(sizeof(char));

  printf("finished malloc\n");

  // fill allocated memory with integers and read back some values
  for(i = 0; i < BUFFERSIZE; ++i)
  {
    mybuffer->buffer[i] = i;
    mybuffer->bools[i] = true;
    bufferinfo->whichbuffer = (unsigned int)(i/100);
  }


  MemFree(bufferinfo);
  MemFree(mybuffer);

  if(pCh)
  {
    MemFree(pCh);
  }

  return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

Mak*_*kis 13

您可以在包装器中分配一些额外的字节,并放置一个id(如果您希望能够耦合malloc()和free())或只是那里的大小.只需要malloc()更多的内存,将信息存储在内存块的开头,并移动指针,返回前面的那么多字节.

顺便说一句,这也可以很容易地用于栅栏指针/指纹等.

  • 确保返回的指针具有相同的对齐方式,或者比malloc返回的指针更好,以防万一. (3认同)