gpt4 book ai didi

c - malloc + size_t * 3 的地址是否为任何类型对齐?

转载 作者:太空狗 更新时间:2023-10-29 15:53:54 24 4
gpt4 key购买 nike

我正在构建一种动态数组( vector ),但不是将数据(通常是 void *)嵌入到 struct vector 中,而是保留struct vector + 字节 block 的空间,使用 size_t 数组的示例:

#include <stdio.h>
#include <stdlib.h>

struct vector {
size_t capacity;
size_t typesize;
size_t size;
};

#define VECTOR(v) ((struct vector *)((unsigned char *)v - sizeof(struct vector)))

static void *valloc(size_t typesize, size_t size)
{
struct vector *vector;
unsigned char *data;

data = calloc(1, sizeof(*vector) + typesize * size);
if (data == NULL) {
return NULL;
}
vector = (struct vector *)data;
vector->typesize = typesize;
vector->capacity = size;
vector->size = 0;
return data + sizeof(*vector);
}

static void *vadd(void *data)
{
struct vector *vector = VECTOR(data);
unsigned char *new;
size_t capacity;

if (vector->size >= vector->capacity) {
capacity = vector->capacity * 2;
new = realloc(vector, sizeof(*vector) + vector->typesize * capacity);
if (new == NULL) {
return NULL;
}
vector = (struct vector *)new;
vector->capacity = capacity;
vector->size++;
return new + sizeof(*vector);
}
vector->size++;
return data;
}

static size_t vsize(void *data)
{
return VECTOR(data)->size;
}

static void vfree(void *data, void (*func)(void *))
{
struct vector *vector = VECTOR(data);

if (func != NULL) {
for (size_t iter = 0; iter < vector->size; iter++) {
func(*(void **)((unsigned char *)data + iter * vector->typesize));
}
}
free(vector);
}

int main(void)
{
size_t *data;

data = valloc(sizeof(size_t), 1);
if (data == NULL) {
perror("valloc");
exit(EXIT_FAILURE);
}
for (size_t i = 0; i < 10; i++) {
data = vadd(data);
if (data == NULL) {
perror("vadd");
exit(EXIT_FAILURE);
}
data[i] = i;
}
for (size_t i = 0; i < vsize(data); i++) {
printf("%zu\n", data[i]);
}
vfree(data, NULL);
return 0;
}

问题是:malloc (void *) 的结果地址 + struct 的大小对于任何类型?这段代码的行为是否定义明确?

最佳答案

Is the address of malloc + size_t * 3 aligned for any type?

不,不一定。

通过使前缀数据也基本对齐来确定基本对齐

一种方法是使用struct vectormax_align_tunionunion uvector 的大小将是 基本对齐 的倍数。

max_align_t which is an object type whose alignment is as great as is supported by the implementation in all contexts;

union uvector {
max_align_t a;
struct vector {
size_t capacity;
size_t typesize;
size_t size;
} v;
};

union uvector *uvector;
unsigned char *data;

data = calloc(1, sizeof *uvector ...
...
return data + sizeof *uvector;

答案有一些低效 - 在另一个答案中重新设计..

关于c - malloc + size_t * 3 的地址是否为任何类型对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55867320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com