【问题标题】:implementing explicit list memory allocation on array in c在c中的数组上实现显式列表内存分配
【发布时间】: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


    【解决方案1】:

    首先,为了避免给自己带来痛苦,我建议使用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 是指针类型,正如您的大小计算所表明的那样。

    【讨论】:

    • 谢谢,但是当尝试对 void 指针进行指针运算时,这会生成错误“表达式必须是指向完整对象类型的指针”!.. 这是问题的一部分,如何做哮喘而不做演员,你能提供更多信息吗,或者我做错了什么!
    • 问题是你试图直接取消引用一个空指针。带 void 指针的算术运算没有问题,但你不能在没有强制转换的情况下取消引用 void 指针。
    猜你喜欢
    • 2014-12-13
    • 2019-01-17
    • 2021-08-19
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 2018-07-14
    • 1970-01-01
    相关资源
    最近更新 更多