Re: memcpy junk at beginning of buffer
- From: usenet@xxxxxxx
- Date: 29 Dec 2005 20:36:08 GMT
> Im trying to memcpy a buffer from a filled in simple structure.
> When I memcpy and then print the resulting buffer, I see 7 locations
> that have junk before my data starts.
>
> My data structure is:
>
> struct command_pkt {
> char command_num[3];
> char command[100];
> };
>
> typedef command_pkt COMMAND;
You might want to avoid typedefs in this case. There is nothing wrong with
knowing you are dealing with a struct of the type command_pkt when you are
declaring your variables.
> The relevant portion is the following:
If possible, please post a complete program that others can compile it and
try running it, instead of only a snippet. There can be a lot of other
things going on that we can't see from here.
> sprintf(tmp,"%s %s",ip,host);
>
> COMMAND *com;
Here you define *com as a pointer, but where does it point to ?
> strcpy(com->command_num,"1");
> strcpy(com->command,tmp);
>
> int len = sizeof(COMMAND);
> unsigned char buf[200];
> if (len > 200) {
> printf("ERROR - len > buf\n");
> return -1;
> }
>
> memset(&buf[0],0,200);
> memcpy(&buf[1],(unsigned char *)&com,len);
A few things are wrong here, of which at least :
- You have declared a pointer to your struct, but you have not allocated
any memory for it. Use malloc() or one of its friends, or declare 'com' as
COMMAND com;
and change your code to
strcpy(com.command_num,"1");
strcpy(com.command,tmp);
- You are copying the *pointer* to your 'com' to the buffer, instead of
'com' itself.
- The size of the pointer to 'com' is probably not 'len' bytes big, so
changes are you are copying other memory as well. This memory might be
yours, or it might not be. This might crash your system or do other nasty
things. Or it might just cause junk in your buffer. (which is nasty
enough)
- You are copying up to 200 bytes to the address of buf[1] instead of
buf[0], thus overflowing your buffer by one byte.
> printf("COM buf: <%s>\n",buf);
It surprises me that this printf() outputs anything at all, since the above
code suggests that buf[0] should be zero. But since all kind of funny memory
accesses have been done before that, anything could happen here.
> Any ideas why there is junk at the beginning of my buffer?
Some time ago I read a story on this newsgroup about somebody who had demons
fly out of his nose once, when he ran a similar program. Quite painful. You
are lucky to have just junk in your buffer ! :)
_Ico
--
:wq
^X^Cy^K^X^C^C^C^C
.
- Follow-Ups:
- Re: memcpy junk at beginning of buffer
- From: Jeff
- Re: memcpy junk at beginning of buffer
- References:
- memcpy junk at beginning of buffer
- From: Jeff
- memcpy junk at beginning of buffer
- Prev by Date: Re: warning : no new line at end of file
- Next by Date: Re: gets() - dangerous?
- Previous by thread: Re: memcpy junk at beginning of buffer
- Next by thread: Re: memcpy junk at beginning of buffer
- Index(es):
Relevant Pages
|