【问题标题】:Is this custom malloc OK?这个自定义 malloc 可以吗?
【发布时间】:2016-07-14 22:23:02
【问题描述】:

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

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

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

【问题讨论】:

  • 当你需要free时会发生什么?
  • 如果你是 C 新手,为什么要在你能走路之前就跑呢?问题的答案是否定的
  • @EliKorvigo 是的,我看到了;他们提出的解决方案是将指针传递给一个大数组并手动管理里面的内存。这就是我想要做的。
  • @EdHeal 我不需要免费,也不需要担心用完:这是一个非常具体的一次性使用。我只需要不安全的 malloc 而不需要 free (不安全的意思是如果我过去,我对段错误很好,因为我知道我不会过去)。我要问的是,我写的内容是否足够好?
  • 应该是return memory+startIdx;

标签: c pointers memory-management pointer-arithmetic


【解决方案1】:

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

#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. 最大的问题是对齐。返回的指针需要对齐。由于此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() 未编码。如果需要,这种简单的分配方案将需要大量添加。

    【讨论】:

      猜你喜欢
      • 2012-03-04
      • 2014-06-10
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多