开发者

mempcy fail to copy all data

I encounter problem with memcpy in C. Here is t开发者_开发百科he code :

typedef struct {
CPY_IM009_DEF
}message;

message msg;

with CPY_IM009_DEF is a struct in other files. Then I try this

char wx_msg_buf[8192];
memset(wx_msg_buf, 32, sizeof (wx_msg_buf));
memcpy(wx_msg_buf, &msg, sizeof (msg));

when I check the size :

sizeof (msg) = 2140

sizeof (wx_msg_buf) = 8192

But when I check the wx_msg_buf, memcpy only copy part of msg to wx_msg_buf (200 from 2140). What I want to know is why does this happen?If more code required please tell me

Thanx you for the help.


How are you checking? Simply printing the string or looking at it in a debugger? If the message has any '\0' characters in it. It will stop printing at the first one.

To see the whole thing, you can just loop through and print each character. Something like this:

int i;
for(i = 0; i < sizeof(wx_msg_buf); ++i) {
   printf("%02x ", wx_msg_buf[i]);
}


The code looks fine to me. The problem may be with the way you look at it. What is the layout of the underlying structure, and what tools to you use to get the observation about the 2000 bytes?


Check your source data and your result data in a debugger.

It is almost inconceivable that memcpy() has a defect, it's used so widely.


Try once; "memmove" instead of "memcpy".. memcpy() is faster, but it's not safe for moving blocks of memory where the source and destination overlap. memmove() can be used to move memory in those cases.

So better use "memmove".. i think it will solve your problem


Okay, I change :

char wx_msg_buf[8192];

into

char wx_msg_buf[2141];

and now the code work, still I can't understand why the previous won't work

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜