1/17 If I have "foo_bar_baz_struct_t *p, *q;", which of the following
is better?
1. p = malloc(sizeof (foo_bar_baz_struct_t));
memcpy(q, p, sizeof (foo_bar_baz_struct_t));
2. p = malloc(sizeof *p);
memcpy(q, p, sizeof *p);
Thanks.
\_ 1 is far more obvious for me...
\_ 2 is better if you think you are going to change
what type of struct p points to frequently. 1 is
the preferred way of coding for readability.
\_ Well, I like 2. It's more concise, and you can't screw up
and put in the wrong type in the sizeof.
\_ My vote is for #2 too. Also, I like *q = *p better than
the memcpy. And no, for someone familiar with C, I don't
see how the memcpy makes anything clearer.
\_I don't think that they are necessarily the same in straight C.
In C++ that may be equivalent. Also, shouldn't you be mallocing q?
\_I don't think that they are necessarily the same in straight
C. In C++ that may be equivalent. Also, shouldn't you be
malloc'ing q?
\_ It seems so. Also, shouldn't OP be checking if
the pointer returned by malloc is NULL?
\_ You are exactly backwards. -pld
\_ you think wrong. In C bar=foo does a shallow copy.
\_ Yes, we know this, but the question is does memcpy
do a shallow copy also? Somehow I think this is
wrong. From what I remember memcpy does a bit for bit
copy, which is very problematic once you get into things
like structs and classes. The two may not be equivalent,
and it certainly would come out different in the
object code.
\_ How do shallow and bit-for-bit differ? Very curious-pld
\_ It may or may not, it depends on what the struct
actually contains. That's the crux of the argument.
If the struct contains a class or class pointer(assuming
you are doing this in c++) you
run into all sorts of different behaviors.
\_ The proper answer is "they're identical" -pld
\_ No they are not. Shallow copy copies pointers,
deep copy copies objects also (potentially
using copy constructors, etc.)
\_ Is it possible that this is a Visual C++ extension for C?
Possibly, if they are on crack. You can do this in C++ by
defining your own operator= method. |