1
我一直在寻找到一些内存管理(pool
+ malloc
+ free
)实现使用链表,我发现,在大部分时间里的每一个节点是这样的:为什么接近节点顶部的下一个指针?
typedef struct node{
int usedSize;
node* next;
char mem[100];
}
然后free(ptr)
必须是:
free(void* ptr){
node* item = (node*)((char*)ptr - sizeof(node*) - sizeof(int));
\\some code to put the "item" back to the pool
}
我的问题是这样的: 为什么我们不该把char mem[100];
在结构的开头,以避免“指针操作”?
结果是:
typedef struct node{
char mem[100]; // moved to the beginning
int usedSize;
node* next;
}
,然后free(ptr)
简单:
free(void* ptr){
node* item = (node*)((char*)ptr);
\\some code to put "item" back to the pool
}
感谢。
如果所有分配完全是100个字节,那么这将工作正常。但是如果分配的大小不同,你如何找到分配的大小?在分配之前立即设置大小使其变得简单。 – rici
thatnks @rici但我不需要找到它,我可以使用 node-> usedSize 我错过了什么? – mvk
谢谢@jxh回答(3),我不知道。 – mvk