Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is struct copying with memcpy() legal?

Tags:

c

casting

memcpy

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);
like image 872
K. Biermann Avatar asked Dec 14 '25 13:12

K. Biermann


1 Answers

Legal. According to memcpy manual: The memcpy() function copies n bytes from memory area src to memory area dest. The memory areas must not overlap. Use memmove(3) if the memory areas do overlap.

So it doesn't care about types at all. It just does exactly what you tell it to do. So use it with caution, if you used sizeof(a) instead sizeof(b) you might've overwritten some other variables on the stack.

like image 132
manish ma Avatar answered Dec 16 '25 09:12

manish ma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!