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?
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:
memcpy
, as structure assignment requires both source and destination to be aligned properly.memcpy
, and factor this additional information into the size field.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.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 memcpy
ing structures, as structure assignment can, and often is, overloaded to do additional things such as deep copies or reference count management.