0

It's been a while since I have used C and am finding some issues in my code. I have a struct as such:

struct packet
{
char seq[4];
char type[4];
char src[10];
char dst[10];
char payload[MAX_BUF_LEN]; //predefined buffer length constant
}

Then when receiving a string of characters separated by spaces, I want to copy each of these "fields" into one of the corresponding struct packet variables. Here is what I have:

strcpy(temp_buf, buf);
field=strtok(temp_buf, " ");

Example string in temp_buf: "1 send 8273940124 9472849351 hello"

strcpy(inet_packet.seq, field);
field=strtok(NULL, " ");
strcpy(inet_packet.type, field);
field=strtok(NULL, " ");
strcpy(inet_packet.src, field);
field=strtok(NULL, " ");
strcpy(inet_packet.dst, field);
field=strtok(NULL, "\n");
printf("field: %s\n", field); //Shows field="hello"
strcpy(inet_packet.payload, field);

However, on the above example input, inet_packet.type = send82739501249472849351hello So; it appears to be concatenating every successive copy into type? Have tried several different things but still fail to get the expected output.

CChiste
  • 131
  • 1
  • 2
  • 13
  • To make it easy for others to help you, please compose and post an http://www.sscce.org/ – pts Nov 21 '14 at 00:14
  • You write that you have tried several different things. Please post everything you tried (with full source code), the output you received, and why it is not good for you. – pts Nov 21 '14 at 00:14
  • 1
    I'm not sure if this is related to the problem you're having, but I noticed that three of your struct members (type, src and dest) are not big enough to contain both the strings you've provided and the null terminator. – doppelheathen Nov 21 '14 at 00:19

1 Answers1

1

C strings must be NUL-terminated. So your declaration char type[4] is not large enough to hold the string send without overflowing.

Change this declaration to char type[5] and ensure that you do not put a string longer than 4 characters in there.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • That did it. Unexpected behavior for what the root problem was, I thought that the strings would simply be chopped off at the end if that was the issue, good to know though. Thank you. – CChiste Nov 21 '14 at 00:39
  • @user2950936: Yup. `strcpy()` is not very smart and will happily overwrite past the end of its destination buffer. – Greg Hewgill Nov 21 '14 at 00:53