有时,出于性能方面的原因,我可能决定定义一个结构,例如
typedef struct {
size_t capacity;
size_t size;
int offset;
void* data[];
} ring_buffer;在结构本身中内联data。我现在将创建函数定义为
ring_buffer* ring_buffer_create(size_t capacity) {
int struct_size =
sizeof(int) + 2 * sizeof(size_t) +
capacity * sizeof(void*);
ring_buffer* rb = (ring_buffer*)malloc(struct_size);
rb->capacity = capacity;
rb->offset = 0;
rb->size = 0;
return rb;
}只要C编译器不做一些奇怪的字段填充/对齐,这(如果我没有计算错任何东西)将工作得很好。
人们通常是如何处理这种情况的(当然,除了将data定义为指针之外)?
谢谢
发布于 2019-07-19 15:11:50
您的大小计算不正确:结构可能具有嵌入的填充,以确保其某些成员对齐。例如,在64位目标上,int是4字节,而后面的void *data[]数组需要8字节对齐,因此编译器将在data成员之前插入4字节的填充。
大小应按如下方式计算:
size_t struct_size = sizeof(ring_buffer) + capacity * sizeof(void *);或者有可能:
size_t struct_size = offsetof(ring_buffer, data) + capacity * sizeof(void *);请注意,size应该具有类型size_t,并且您应该测试malloc故障,以避免未定义的行为:
ring_buffer *ring_buffer_create(size_t capacity) {
size_t struct_size = sizeof(ring_buffer) + capacity * sizeof(void *);
ring_buffer *rb = malloc(struct_size);
if (rb) {
rb->capacity = capacity;
rb->offset = 0;
rb->size = 0;
}
return rb;
}https://stackoverflow.com/questions/57100991
复制相似问题