Re: memcpy junk at beginning of buffer
- From: JimS <sorry@xxxxxxx>
- Date: Fri, 30 Dec 2005 10:16:01 +1100
On 29 Dec 2005 14:50:02 -0800, "Jeff" <jeep@xxxxxxxxx> wrote:
>Sorry, i realized a couple things after I posted this.
>
>Here's the fully independent version, also fixed char out
>issue vs COMMAND struct:
>
>#include <string.h>
>#include <stdlib.h>
>#include <stdio.h>
>
>struct command_pkt {
> char command[100];
>};
>
>int main()
int main(void)
would be better.
>{
> char out[20];
> strcpy(out,"buffer data");
You had
char out[20]="buffer data";
before, which was fine.
> struct command_pkt *com;
> com = (struct command_pkt *)malloc( sizeof(struct command_pkt) );
com = malloc(sizeof *com);
would be much better. You shouldn't cast the result of malloc because
it hides the error of not #including stdlib.h (which you didn't make).
Much better to use sizeof *com because if the type of com changes
later, the code will still be correct.
> strcpy(com->command,out);
>
> printf("\tCom send: %s\n",com->command);
>
> int len = sizeof(struct command_pkt);
size_t len = sizeof(*com);
would be better.
> unsigned char buf[300];
>
> memcpy(&buf[0],(unsigned char *)&com,len);
Why cast to unsigned char * when memcpy takes void *? All pointers in
C are compatible with void *.
Your bug is here anyway, it should be com, not &com you pass.
memcpy(&buf[0],com,len);
> printf("COM SENDING: <%s>\n",com->command);
> printf("COM buf: <%s>\n",buf);
>
> return 0;
>}
Jim
.
- References:
- memcpy junk at beginning of buffer
- From: Jeff
- Re: memcpy junk at beginning of buffer
- From: usenet
- Re: memcpy junk at beginning of buffer
- From: Jeff
- Re: memcpy junk at beginning of buffer
- From: Jeff
- memcpy junk at beginning of buffer
- Prev by Date: Re: Open Source Community
- 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):