【发布时间】:2019-03-14 04:19:43
【问题描述】:
我有一个在main 函数中初始化的数组,我想用这个数组作为我的内存块。并在其上实现我自己的 malloc 函数。
但是在这个数组上调用我的 malloc 之前,我需要将它作为我自己的内存块启动,这样我就可以使用它了。
现在我有一个名为 init(void *ptr, int size) 的函数,ptr void 指针是数组的开头,size 是数组的大小。
这个函数应该将数组初始化为一个内存块。 我使用的是explicit list allocation(第15页),所以在init中我基本上会在数组的开头有一个全局指针指向,然后我会在内存上设置一个header:
- flag: block is free or allocated 'in init function it will be free'.
- size: the size of the array.
- *next: which points at the next free block.
- *prev: points at the previous free block.
现在我的问题是如何填充标题,我当前的“非功能代码是:
void init_mem(void *ptr, unsigned int size)
{
GLOBAL_POINTER = ptr;
*(char *)ptr = FREEMEM; // FREEMEM is a const which : free memory block
// ptr + 1 is the second spot on the memory block, for the size of the array
*((char *)ptr + 1) = size - sizeof(int) - (sizeof(char *) * 3);
//because the ehole memory block is free now, the next and prev pointers points to the same block
*((char **)ptr + 3) = (char *)ptr;
*((char **)ptr + 4) = (char *)ptr;
}
我现在的问题是设置此信息,问题是:
我是否应该将
ptr转换为原始类型以便我可以使用它,如果是,什么类型是合适的,因为int需要4 个字节,而char需要1 个等等,那么什么是正确的方法,有没有办法通过抛弃来做到这一点。如果我不强制转换,那么如何进行指针运算
*((char *)ptr + 1)以在内存点中移动,因为如果您对 void 指针进行指针运算,它会通过错误expression must be a pointer to a complete object type
非常感谢。
【问题讨论】:
标签: c algorithm pointers memory-management malloc