Copying structure in C with assignment instead of memcpy()

olliezhu picture olliezhu · Nov 8, 2012 · Viewed 37k times · Source

Up until recently, I have only seen copying of structure fields done with memcpy(). In classes and online instructions, copying the contents of one struct into another generally looks like

struct block *b0 = malloc(sizeof(struct block));
struct block *b1 = malloc(sizeof(struct block));
/* populate fields in *b0 */
memcpy(b1, b0, sizeof *b1); /* copy contents of b0 into b1 */
/* free b0, b1 */

However, this task can also be accomplished by a simple assignment replacing the memcpy().

*b1 = *b0; /* dereferenced struct assignment */

Is there good reason why this isn't as widely used (at least in my limited experience)? Are these two methods—assignment and memcpy()—equivalent, or is there some compelling reason to use memcpy() in general?

Answer

bdonlan picture bdonlan · Nov 8, 2012

Both methods are equivalent, and perform a shallow copy. This means that the structure itself is copied, but anything the structure references is not copied.

As for why memcpy is more popular, I'm not sure. Older versions of C did not support structure assignment (although it was a common extension as early as 1978), so perhaps the memcpy style stuck as a way of making more portable code? In any case, structure assignment is widely supported in PC compilers, and using memcpy is more error-prone (if you get the size wrong, Bad Things are likely to happen), and so it's best to use structure assignment where possible.

There are, however, cases where only memcpy works. For example:

  • If you're copying a structure to or from an unaligned buffer - eg, to save/load to/from disk or send/receive on a network - you need to use memcpy, as structure assignment requires both source and destination to be aligned properly.
  • If you're packing additional information after a structure, perhaps using a zero-element array, you need to use memcpy, and factor this additional information into the size field.
  • If you're copying an array of structures, it may be more efficient to do a single memcpy rather than looping and copying the structures individually. Then again, it may not. It's hard to say, memcpy implementations differ in their performance characteristics.
  • Some embedded compilers might not support structure assignment. There's probably other more important things the compiler in question doesn't support as well, of course.

Note also that although in C memcpy and structure assignment are usually equivalent, in C++ memcpy and structure assignment are not equivalent. In general C++ it's best to avoid memcpying structures, as structure assignment can, and often is, overloaded to do additional things such as deep copies or reference count management.