我正在通过C套接字发送一个uint8_t和一个uint16_t,但是由于某些原因,当我尝试从char缓冲区中复制数据时,我一直遇到段错误。

// sending code:
uint8_t a_t = A;
uint16_t b = htons(B);

int len = sizeof(uint8_t) + sizeof(uint16_t); // should be 3 bytes
char buf[3];
memcpy(&buf, &cmd_t, sizeof cmd_t);
size_t offset = sizeof(uint8_t);
memcpy(&buf[offset], &cmd, sizeof cmd); // this works
send(sockfd, buf, len, 0);

// receiving code:

char buf[256];
int nbytes = recv(sockfd, buf, sizeof(buf), 0);
if (nbytes >0 ){
handleData(buf, nbytes); // buf = "\0\0-100/156"
}



 void handleData(char *buf, int nbytes) {
// buf = "" ????
    uint8_t a;
    uint16_t b;
    memcpy(&a, buf, sizeof(uint8_t));
    memcpy(&b, buf[1], sizeof(uint16_t)); // <-- Segfaults here
    int B = ntohs(b); // convert b to actual number
    }


我在这里做错了什么?

最佳答案

memcpy(&b, buf[1], sizeof(uint16_t)); // <-- Segfaults here


这是因为buf[1]char,并且memcpy需要一个连贯的地址(并且从buf[1]读取会产生垃圾)。
正如@joop在他的评论中所述,您应该宁愿:

memcpy(&b, buf+1, sizeof(uint16_t));


要么:

memcpy(&b, &buf[1], sizeof(uint16_t));


在这里,将memcpy的地址赋予buf,其偏移量为1

关于c - 在memcpy上将segfault从套接字recv()转换为uint16_t,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25789324/

10-11 22:56
查看更多