Preference between memcpy and dereferencing

When copying a known structure in memory, do you prefer to use memcpy or dereference? What for? In particular, 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;
 }

Do you prefer method 1 or method 2? I looked at the assembly generated by gcc, and it seems that method 2 uses fewer instructions than method 1. Is this assumed that method 2 is preferable in this case? Thanks.

+7
c memory dereference memcpy
source share
2 answers

I canโ€™t come up with any good reason to use memcpy() instead of assigning a structure when copying (unless you need to do a deep copy or something related to a struct hack or a flexible member of an array, none of which apply in this case) .

They have exactly the same semantics, and assignment (a) probably gives the compiler more options for optimization, and (b) has a lower risk of getting the wrong size.

Some very old C compilers probably do not support structure assignment, but this is no longer a serious problem.

(There are additional reasons to prefer assignment in C ++, but your question is about C.)

By the way, parentheses in

 (*pto) = (*pfrom); 

Not needed; unary * binds tight enough to:

 *pto = *pfrom; 

is correct and clear enough for most readers.

+13
source share

For the same reason you were talking about, I would prefer method 2 (dereferencing one). Memcpy performs a byte copy and has an overhead for calling the function, while dereferencing only makes a copy and has no additional overhead.

Disclosure and purpose are also more readable (especially when you omit the extra parentheses:

 *dest = *src; 

)

+2
source share

All Articles