简体   繁体   中英

C - strcpy appears to be concatenating successive values stored in a struct

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM