存在一些问题:
-
最大的问题是对齐。返回的指针需要对齐。自从这以后
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);
-
没有检测到内存不足。
-
避免重复使用标准库名称。代码可以
define
如果需要的话,可以稍后再进行。
// void* malloc(int size, int* bytesUsed, uchar* memory);
void* RG_malloc(int size, int* bytesUsed, uchar* memory);
// if needed
#define malloc RF_malloc
-
malloc()
需要不同类型的分配:
size_t
int
.
// void* malloc(int size, int* bytesUsed, uchar* memory);
void* malloc(size_t size, size_t* bytesUsed, uchar* memory);
-
不需要铸造。
// return (void*)(memory+startIdx);
return memory + startIdx;
-
使用更清晰
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()