tags:

views:

91

answers:

5

Hello all,

I encounter problem with memcpy in C. Here is the 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.

+3  A: 

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]);
}
Evan Teran
sizeof(msg) since that is what's used in the memcpy().
Heath Hunnicutt
@Heath: Sure, I figured he may as well take a look at the whole buffer :-P.
Evan Teran
I check it using GDB, put a break point then print both msg and wx_msg_buf
Willy
It's probably treating wx_msg_buf ad a C string is what Evan is saying. Printing it in gdb (`print wx_msg_buf`) will take you only to the first null. You need to dump the entire contents of the buffer to be sure.
JeremyP
+1  A: 

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?

Pavel Radzivilovsky
when I print the value in GDB it show the result like this :(gdb) p wx_msg_buf$1 = "0000L_NAME00000POSLH000FN_NAME", '0' <repeats 40 times>, "4800010120100101010100COM_HDR0B.MX_BUFFER", '0' <repeats 89 times>
Willy
A: 

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.

djna
I know that's why I'm confused.I use memcpy() several time in the code, but only this line that have problem
Willy
A: 

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

ram
msg and wx_msg_buf are different variables. They do not overlap, so you don't get any additional safety with memmove.
harper
A: 

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

Willy
You should have put this as an edit to your question.
nategoose