【问题标题】:memcpy() segmentation fault [closed]memcpy()分段错误[关闭]
【发布时间】:2014-07-01 02:25:18
【问题描述】:

我正在序列化一个结构以通过套接字发送,但是当我尝试反序列化 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 上犯了一个错误,但我不明白是什么

【问题讨论】:

  • 代码不会像写的那样编译。
  • 这是什么50?在每个 , 后面留一个空格,让您的代码更具可读性。
  • 使用你的调试器看看出了什么问题。是从源读取还是写入目标有问题?

标签: c pointers segmentation-fault memcpy


【解决方案1】:

我能看到的一个问题:

unsigned char buff

应该改为

unsigned char * buff

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

【讨论】:

    【解决方案2】:

    这里:

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

    应使用msg.msg的地址:

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

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

    【讨论】:

      【解决方案3】:

      整个程序可能不会按照您的计划进行。我不知道 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 :(
      

      【讨论】:

        【解决方案4】:

        不是这个

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

        尝试这样做

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-13
          • 1970-01-01
          相关资源
          最近更新 更多