When copying a known struct in memory, would you prefer using memcpy or dereference? why?
Specifically, in the following code:
#include <stdio.h>
#include <string.h>
typedef struct {
int foo;
int bar;
} compound;
void copy_using_memcpy(compound *pto, compound *pfrom)
{
memcpy(pto, pfrom, sizeof(compound));
}
void copy_using_deref(compound *pto, compound *pfrom)
{
*pto = *pfrom;
}
int main(int argc, const char *argv[])
{
compound a = { 1, 2 };
compound b = { 0 };
compound *pa = &a;
compound *pb = &b;
// method 1
copy_using_memcpy(pb, pa);
// method 2
copy_using_deref(pb, pa);
printf("%d %d\n", b.foo, b.bar);
return 0;
}
Would you prefer method 1 or method 2? I looked at the assembly generated by gcc, and it seems that method 2 uses less instructions than method 1. Does it imply that method 2 is preferable in this case? Thank you.
I can’t think of any good reason to use
memcpy()rather than an assignment when copying a struct (as long as you don’t need to do a deep copy or something involving the struct hack or a flexible array member, none of which apply in this case).They have exactly the same semantics, and the assignment (a) likely gives the compiler more opportunities for optimization, and (b) has less risk of getting the size wrong.
Some very old C compilers probably didn’t support struct assignment, but that’s no longer a significant concern.
(There are additional reasons to prefer assignment in C++, but your question is about C.)
Incidentally, the parentheses in
are unnecessary; the unary
*binds tightly enough that this:is both correct and sufficiently clear to most readers.