C - memcpy()分段故障



我正在序列化一个结构体,通过套接字发送,但当我试图反序列化内存时,我返回了一个分段错误

这是我的序列化代码:

unsigned char serialize(msg_t msg)
{
    unsigned char out_buf[sizeof(msg.id)+sizeof(msg.msg)];
    unsigned char *p = out_buf;
    //Serialize id
    unsigned int idX = htonl(msg.id);
    memcpy(p,&idX,sizeof(idX));
    p += sizeof(idX);
    //Serialize msg
    memcpy(p,msg.msg,sizeof(msg.msg));
    p += sizeof(msg.msg);
    return out_buf;
}

就是反序列化(that not works)

msg_t deserialize(unsigned char buff)
{
    msg_t msg;
    unsigned char *p = buff;
    unsigned int *idX = malloc(sizeof(unsigned int));
    char *mess = malloc(sizeof(50));
    printf("Deserialization startn");
    //deserialize id
    memcpy(idX,p,sizeof(unsigned int));
    msg.id = ntohl(idX);
    p += sizeof(idX);
    printf("ID deserializzaton");
    //deserialize msg
    memcpy(msg.msg,p,sizeof(msg.msg));
    printf("msg deserializzaton");
    return msg; 
}

,这是结构体:

typedef struct{
    int id;
    char* msg;
} msg_t;

我知道我在idX上犯了一个错误,但是我不明白

我看到一个问题:

unsigned char buff

改为

unsigned char * buff

不是吗?并且在传入

之前确保buff被充分分配

此处:

memcpy(msg.msg,p,sizeof(msg.msg));

使用msg.msg的地址:

memcpy(&msg.msg, p, sizeof(msg.msg));

(演示你的代码编译没有警告)?

整个程序可能不会按照您的计划执行。我不知道味精是否。MSG是一个指针或数组。在第一种情况下,你的尺寸可能是错误的。

char *mess = malloc(sizeof(50)); // sizeof is designed to return the size of the type, I have no clue whether this will be 4 bytes or 50. My guess is, it will return 4
memcpy(idX,p,sizeof(unsigned int)); // unsigned or not doesn't matter for sizeof
unsigned char *p = buff; // pointer == dereferenced variable ==> not good :(

代替

//deserialize msg
    memcpy(msg.msg,p,sizeof(msg.msg));

Try doing this

msg.msg = malloc(msg.msg, p, sizeof(p));

最新更新