我有以下代码,不确定是使用结构对齐还是 memcpy 将结构 A 复制到自定义“堆栈”字符/字节数组上。
以下两种代码选项或任何完全错误的东西有什么好处/坏处吗?
必要的结构/功能。
struct B {
int type;
struct B *prev;
}
struct A {
struct B base;
int n;
struct B *another;
char name[1]; /* Struct hack */
};
void align(char **ptr, int n) {
intptr_t addr = (intptr_t)*ptr;
if(addr % n != 0) {
addr += n - addr % n;
*ptr = (char *)addr;
}
}
选项 1:结构分配
void struct_assignment() {
char *stack = malloc(400*1000);
char *top_of_stack = stack + 3149; /* Just an example */
struct A *var = (struct A *)top_of_stack;
align((char **)&var, sizeof(struct B)); /* Most restrictive alignment member in struct A */
var->base.type = 1;
var->base.prev = NULL;
var->another = (struct base *)var;
char *name = "test";
var->n = strlen(name) + 1;
strcpy(var->name, name);
top_of_stack = (char*)var + sizeof(*var)+ (var->n - 1); /* -1 for name[1] */
}
选项 2:内存
void memcpying() {
char *stack = malloc(400*1000);
char *top_of_stack = stack + 3149; /* Just an example */
struct A var;
var.base.type = 1;
var.base.prev = NULL;
var.another = NULL;
char *name = "test";
var.n = strlen(name) + 1;
strcpy(var.name, name);
char *aligned_ptr = top_of_stack;
align(&aligned_ptr, sizeof(struct B)); /* Most restrictive alignment member in struct A */
memcpy(aligned_ptr, &var, sizeof(var) + (var.n - 1); /* -1 for name[1] */
struct A *var_ptr = (struct A*)aligned_ptr;
var_ptr->another = (struct B *)var_ptr;
top_of_stack = aligned_ptr + sizeof(var)+ (var.n - 1); /* -1 for name[1] */
}
选项 1 甚至是结构赋值吗?
这两个选项会导致相同的填充和对齐吗?
目标架构的字节序是否会影响选项 1?