Bum*_*Bee 6 c memory malloc memory-management allocation
我试图在C中编写一个自定义分配器用于调试目的(作为练习),我将使用单个链表来使用First Fit算法将自由列表保存在一起.我在下面展示了我想在"空内存节点"中创建的结构.
如何在内存的前几个字节处编写头块(一个特定的联合),我得到(我使用malloc()来初始获得一块内存)以便剩余的字节是空闲的?
这是我正在使用的联盟:
/*Define Header Structure for proper alignment*/
union header {
struct{
union header* next;
unsigned size ; /*Make it size_t*/
}s;
double dummy_align_var;
};
-------------------------------------------------------------------------------
|Next |Size of |16Byte| User is concerned only about |16Byte| |
|Free Memory |Allocated|Header| this portion of memory |Footer|Checksum |
|Address |Block |Picket| and has no knowledge of rest |Picket| |
-------------------------------------------------------------------------------
|-------Header---------| ^Address Returned to user
^------User Requested Size-----^
^-------------Memory Obtained From The Operating System-----------------------^
*/
Run Code Online (Sandbox Code Playgroud)
[编辑]根据提供的建议更改块结构.
你为什么使用工会?只需使用 astruct
并返回&dummy_align_var
给用户作为空闲块的开始。
哦,由于这是为了调试,我建议您添加一个 mungwall:在用户区域的两侧放置 16 个字节,并用某种模式填充它们(例如 0xdeadbeef,重复四次)。在检查过程中free()
这些字节没有改变。
[编辑] 这是一些伪代码:
struct header {
struct header * next;
unsigned size;
// put mungwall here
double user_data;
};
init()
int blockSize = 1024;
char * bigMem = original_malloc(blockSize);
struct header * first = (struct header *)bigMem;
first->next = NULL;
first->size = blockSize - (sizeof(struct header) - sizeof(double));
Run Code Online (Sandbox Code Playgroud)