代码之家  ›  专栏  ›  技术社区  ›  Elliot Gorokhovsky

这个定制malloc可以吗?

  •  -5
  • Elliot Gorokhovsky  · 技术社区  · 8 年前

    我需要为GPU编程编写一个自定义malloc。这能正常工作吗?

    void* malloc(int size, int* bytesUsed, uchar* memory){
      int startIdx = (*bytesUsed);
      (*bytesUsed) += size;
      return (void*)(memory+startIdx);
    }
    

    我是C编程的新手,我可能会犯一些与指针算法相关的错误或其他什么 bytesUsed 将索引提供给 memory 第一个空闲地址,因此您将其递增 size 然后将增量索引作为指针返回。

    2 回复  |  直到 8 年前
        1
  •  2
  •   lost_in_the_source    8 年前

    我不确定这个简单的基于堆栈的解决方案是否适用于您

    #include <stdint.h>
    const size_t ALLOCSIZE = 1024;
    typedef uint8_t byte;
    
    static byte buf[ALLOCSIZE];
    static byte *pbuf = buf;
    
    byte *alloc(size_t n)
    {
        /* if there is room */
        if (buf + ALLOCSIZE - pbuf >= n) {
            pbuf += n;
            return pbuf - n;
        } else
            return NULL;
    }
    

    我没有提供 free

        2
  •  1
  •   chux    8 年前

    存在一些问题:

    1. 最大的问题是对齐。返回的指针需要对齐。自从这以后 malloc() 未给定所需的指针类型,请使用 max_align_t “这是一种对象类型,其对齐方式与所有上下文中的实现所支持的一致性一样好”C11dr§7.19 2.注: *bytesUsed 也需要这种调整。因此,如果其他代码影响它,应该应用类似的代码。

      if (size%sizeof(max_align_t)) {
        size += sizeof(max_align_t) - size%sizeof(max_align_t);
      }
      // or
      size = (size + sizeof(max_align_t) - 1)/sizeof(max_align_t)*sizeof(max_align_t);
      
    2. 没有检测到内存不足。

    3. 避免重复使用标准库名称。代码可以 define 如果需要的话,可以稍后再进行。

      // void* malloc(int size, int* bytesUsed, uchar* memory);
      void* RG_malloc(int size, int* bytesUsed, uchar* memory);
      
      // if needed
      #define malloc RF_malloc
      
    4. malloc() 需要不同类型的分配: size_t int .

      // void* malloc(int size, int* bytesUsed, uchar* memory);
      void* malloc(size_t size, size_t* bytesUsed, uchar* memory);
      
    5. 不需要铸造。

      // return (void*)(memory+startIdx);
      return memory + startIdx;
      
    6. 使用更清晰 unsigned char uchar ,希望不是别的东西。

    把这些放在一起

    void* malloc(size_t size, size_t* bytesUsed, unsigned char* memory){
      size = (size + sizeof(max_align_t) - 1)/sizeof(max_align_t)*sizeof(max_align_t);
      if (RG_ALLOC_SIZE - *bytesUsed > size) {
        return NULL;
      }
      size_t startIdx = *bytesUsed;  // See note above concerning alignment.
      *bytesUsed += size;
      return memory + startIdx;
    }
    

    此外, RG_free()