在 C 语言中对数组实现显式列表内存分配



我有一个在函数中初始化main数组,我想用这个数组作为我的内存块。 并在上面实现我自己的 malloc 函数。 但是在这个数组上调用我的 malloc 之前,我需要将其作为我自己的内存块启动,以便我可以使用它。

现在我有一个名为init(void *ptr, int size)ptrvoid 指针是数组的开头,size是数组的大小。

此函数应该将数组作为内存块启动。 我使用的是显式列表分配(第 15 页(,所以在 init 中,我基本上会在数组的开头有一个全局指针点,然后我将在内存上设置一个标头:

- 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 个字节,依此类推,那么正确的方法是什么,有没有办法用 outcast 来做到这一点。

  • 如果我不投射,那么如何做指针算术*((char *)ptr + 1)在记忆点移动,因为如果你在 void 指针上做指针算术,它会通过错误expression must be a pointer to a complete object type

谢谢。

首先,为了避免给自己带来悲伤,我建议使用void指针进行所有指针算术,然后将结果转换为适当的指针类型。例如,在行中

*((char **)ptr + 3) = (char *)ptr;

您实际上是在添加3*sizeof(char**)而不是 3 个字节。使用void*算术可以解决此问题。C 语言中int的大小可以是 4 或 8 个字节,具体取决于平台,因此您需要使用sizeof.我认为这就是你想要的:

void init_mem(void* ptr, unsigned int size)
{
GLOBAL_POINTER = ptr;
*(void**)ptr = FREEMEM; // FREEMEM is a const which : free memory block
// the second spot on the memory block, for the size of the array
*(unsigned int*)(ptr + sizeof(void*)) = size - sizeof(unsigned int) - 3 * sizeof(void*);
//because the ehole memory block is free now, the next and prev pointers points to the same block
*(void**)(ptr + sizeof(void*) + sizeof(unsigned int)) = ptr;
*(void**)(ptr + 2 * sizeof(void*) + sizeof(unsigned int)) = ptr;
}

假设FREEMEM是指针类型,正如您的大小计算似乎表明的那样。

最新更新