【发布时间】:2010-10-25 12:32:55
【问题描述】:
编程语言: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;
}
【问题讨论】:
-
我认为 MemAlloc 中不需要两个 malloc()。只需编写一个宏来确定一个合适的对齐大小(或使用 64 位,我认为这对每种情况都足够了)并在分配内存之前按该数量添加 nSize。
-
谢谢 Makis。我在32位平台上。我已经更新了我的实现以在 MemAlloc 中使用单个 malloc。我不明白对齐的重点。如果不是要求太多,您能否在我的实施中指出这可能是一个问题。据推测,如果传递给 MemFree 或从 malloc 返回的指针已经没有对齐,那么没有什么可以做的,因为如果我不使用我的包装器,这些将是未对齐的,对吧?
-
这里有一个关于这个问题的很好的解释:goingware.com/tips/getting-started/alignment.html 我也会有 32 位的大小信息,这应该可以解决这个问题。问题可能是这样的:您从位置 X 开始保留内存,前两个字节是您的大小信息,因此您将 x+2 返回给调用者。但是,如果对齐是 4 个字节,您可能会遇到问题。所以检查 size_t 的大小,或者如果你想要可移植的代码,你需要定义一些宏。
-
好的。谢谢。 sizeof(size_t) 是 4 个字节。我实际上打算使用 uint32_t 使其更明确
标签: c dynamic-memory-allocation