Copying data using memcpy
I am doing a memcpy of clsf_ptr to upclsf
开发者_C百科memcpy(&upclsf, &clsf_ptr, sizeof(struct classifier));
while debugging using gdb i checked the memory address of upclsf when i did print &upclsf i got
(gdb) p &upclsf
$1 = (struct classifier **) 0xbffff184
when i did print upclsf i got
(gdb) p upclsf
$2 = (struct classifier *) 0x2e312e31
which is the address here i am not able to understand, here upclsf is an instance of the structure classifier
GDB disagrees — upclsf
is not a struct classifier
, it is a pointer. Note that the two answers have different types. The first one (&upclsf
) is struct classifier **
, the second one (upclsf
) is struct classifier *
. Here is the memory layout:
addr 0xbffff184 / upclsf: pointer to 0x2e312e31
addr 0x2e312e31 / *upclsf: (structure data)
You want to change your memcpy
to:
memcpy(upclsf, &clsf_ptr, sizeof(struct classifier));
Or possibly:
memcpy(upclsf, clsf_ptr, sizeof(struct classifier));
Note that memcpy
will wantonly destroy data and is not type-safe! Therefore you have to be extra careful when you use it to ensure that the types you give it are correct. I suggest defining the following function:
static inline void
classifier_copy(struct classifier *dest, struct classifier const *src)
{
memcpy(dest, src, sizeof(*dest));
}
This will catch type errors. I make one of these for any structure I copy more than once or twice.
精彩评论