开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜