memcpy()分段错误

时间:2014-05-13 12:06:24

标签: c pointers segmentation-fault memcpy

我将一个结构序列化为通过套接字发送但是当我尝试反序列化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;
}

那就是反序列化(那不起作用)

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 start\n");

    //deserialize id
    memcpy(idX,p,sizeof(unsigned int));
    msg.id = ntohl(idX);
    p += sizeof(idX);
    printf("ID deserializzato\n");

    //deserialize msg
    memcpy(msg.msg,p,sizeof(msg.msg));
    printf("msg deserializzato\n");

    return msg; 
}

这是结构:

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

我知道我在使用idX时犯了一个错误,但我无法理解

4 个答案:

答案 0 :(得分:2)

我可以看到一个问题:

unsigned char buff

应改为

unsigned char * buff

不是吗? 并确保buff在传入之前已充分分配

答案 1 :(得分:0)

这里:

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

应使用msg.msg的地址:

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

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

答案 2 :(得分:0)

整个计划可能无法按照您的计划行事。我不知道msg.msg是指针还是数组。在第一种情况下,你的sizeof可能是错误的。

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 :(

答案 3 :(得分:0)

而不是这个

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

尝试这样做

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