Lets say I have two structs:
typedef struct {
uint64_t type;
void(*dealloc)(void*);
} generic_t;
typedef struct {
uint64_t type;
void(*dealloc)(void*);
void* sth_else;
} specific_t;
The common way to copy to the simpler struct would be:
specific_t a = /* some code */;
generic_t b = *(generic_t*)&a;
But this is illegal because it violates strict aliasing rules.
However, if I memcpy
the struct I only have void
pointers which are not affected by strict aliasing rules:
extern void *memcpy(void *restrict dst, const void *restrict src, size_t n);
specific_t a = /* some code */;
generic_t b;
memcpy(&b, &a, sizeof(b));
Is it legal to copy a struct with memcpy
like this?
An example use case would be a generic deallocator:
void dealloc_any(void* some_specific_struct) {
// Get the deallocator
generic_t b;
memcpy(&b, some_specific_struct, sizeof(b));
// Call the deallocator with the struct to deallocate
b.dealloc(some_specific_struct);
}
specific_t a = /* some code */;
dealloc_any(&a);