编程语言: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 …Run Code Online (Sandbox Code Playgroud)