我正在尝试使用以下结构将收到的数据放入:
typedef struct packet {
uint8_t magic;
uint8_t version;
uint16_t body_length;
char *body;
} packet;
这是打印功能:
void displayPacket (struct packet p){
printf("Magic : %u\n",p.magic);
printf("Version : %u\n",p.version);
printf("Body Length: %d\n",ntohs(p.body_length));
printf("Body : %s\n",p.body);
}
在我的主要工作中,我正在尝试将接收到的数据保存在我的结构中:
unsigned char reply[1024];
struct packet reply_packet;
reply_packet.body = malloc(1021);
reply_packet.body[1020] = '\0';
rc = recvfrom(s,&reply_packet,sizeof(reply_packet),0,NULL,NULL);
displayPacket(reply_packet);
free(reply_packet.body);
close(s);
输出:
Magic : 95
Version : 1
Body Length: 1008
[1] 4741 segmentation fault ./network
Magic、Version、Body Length 是数据包开头的预期输出。由于其他对等方遵循的协议,数据包的最大限制大小为 1024 字节。
但是,我的 displayPacket 函数引起了分段错误,更准确地说是这一行:
printf("Body : %s\n",p.body);
如果可以提供帮助,这是 valgrind 输出:
==4886== Invalid read of size 1
==4886== at 0x4C32CF2: strlen (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4886== by 0x4E994D2: vfprintf (vfprintf.c:1643)
==4886== by 0x4EA0F25: printf (printf.c:33)
==4886== by 0x108EFD: displayPacket (network.c:143)
==4886== by 0x1090FF: main (network.c:189)
==4886== Address 0x3030000000000000 is not stack'd, malloc'd or (recently) free'd
==4886==
==4886==
==4886== Process terminating with default action of signal 11 (SIGSEGV)
==4886== General Protection Fault
==4886== at 0x4C32CF2: strlen (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4886== by 0x4E994D2: vfprintf (vfprintf.c:1643)
==4886== by 0x4EA0F25: printf (printf.c:33)
==4886== by 0x108EFD: displayPacket (network.c:143)
==4886== by 0x1090FF: main (network.c:189)
尽管它看起来很微不足道,但它一直困扰着我几个小时......
预期的输出将是数据包中其余内容的内容。到目前为止,我已经能够做到。
请问您有什么解决方案来解决这个问题?
谢谢。
编辑 1:
通过像这样修改结构解决了分段错误问题:
typedef struct packet {
uint8_t magic;
uint8_t version;
uint16_t body_length;
char body[1021];
} packet;
和其余的代码:
unsigned char reply[1024];
struct packet reply_packet;
reply_packet.body[1020] = '\0';
rc = recvfrom(s,&reply_packet,sizeof(reply_packet),0,NULL,NULL);
printf("body[0] %d\n",reply_packet.body[0]);
displayPacket(reply_packet);
close(s);
displayPacket 保持不变。