2016-07-14 21 views
-5

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

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

我是新的C++编程,我很可能使指针算术相关的错误或东西...的想法是bytesUsed给你的索引,第一个免费的地址memory,使您可以通过增加它size,然后将增加后的索引作为指针返回。

+0

如果你在POSIX检查http://linux.die.net/man/2/sbrk – stackptr

+1

当你需要'免费'时会发生什么? –

+0

@OliverCharlesworth我不需要自由;当工作组完成所有内存被占用并重新用于下一个工作组时。 (我使用的是openCL)。 –

回答

1

有一些问题:

  1. 最大的问题是对齐。返回的指针需要对齐。由于此malloc()未给出所需的指针类型,请使用max_align_t“这是一种对齐类型,其对齐方式与实现在所有上下文中支持的对齐类型一样大”C11dr§7.192.注意:*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 charuchar,这希望不是别的东西。

把所有这些组合起来

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()不编码。如果需要,这个简单的分配方案将需要大量的增加。

2

我不知道,如果这个简单的基于堆栈的解决方案会为你工作

#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,因为你说你没必要取消分配。