使用struct data无效应用'sizeof'和编译错误

时间:2016-02-01 10:07:11

标签: c segmentation-fault sizeof calloc

我创建了一个我想通过套接字发送的数据类型。 我收到编译错误和分段错误错误。 我得到的编译错误是error: invalid application of ‘sizeof’ to incomplete type ‘struct udp_msg_t’,而当我执行memcpy时发生了分段错误。我做错了什么?

以下是我的一些代码:

这是我所关注的结构:

typedef struct udp_msg {
    unsigned int udp_eid;
    u_char   udp_prefix;
    unsigned int udp_loc;
} udp_msg_t;

在方法中,我分配内存和值:

void method(){
    udp_msg_t * udp_msg;

    udp_msg = (struct udp_msg_t * )calloc(1, sizeof(struct udp_msg_t));
    udp_msg->udp_eid = eid.u.prefix4.s_addr;
    udp_msg->udp_prefix = eid.prefixlen;
    udp_msg->udp_loc = loc->rloc.rloc.s_addr;

    send_rloc_udp_to_floodlight(udp_msg);
}

此方法实际上通过套接字发送数据:

int send_rloc_udp_to_floodlight(udp_msg_t message) {
    struct sockaddr_in si_other;
    int s, i, slen = sizeof(si_other);
    char buffer[9];

    if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
        printf("socket");
    }

    memset((char *) &si_other, 0, sizeof(si_other));

    si_other.sin_family = AF_INET;
    si_other.sin_port = htons(8888);

    if (inet_aton("127.0.0.1", &si_other.sin_addr) == 0) {
        fprintf(stderr, "inet_aton() failed\n");
        exit(1);
    }


    memcpy(buffer, (char *) message.udp_eid, sizeof(unsigned int));
    memcpy(&buffer[4], (char *) message.udp_prefix, sizeof(char));
    memcpy(&buffer[5], (char *) message.udp_loc, sizeof(unsigned int));

    //send the message
    if (sendto(s, buffer, strlen(buffer), 0, (struct sockaddr *) &si_other,
            slen) == -1) {
        printf("sendto()");
    }

    close(s);
    return 0;
}

2 个答案:

答案 0 :(得分:2)

sizeof(struct udp_msg_t)

不正确 - 它应该是

sizeof(udp_msg_t)

sizeof(struct udp_msg)

演员同上:

(struct udp_msg_t * )

在调用calloc之前,虽然这应该被移除,因为它是redundant and potentially dangerous

答案 1 :(得分:1)

我没有正确获取struct字段的指针值。 memcpy的正确做法是:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
  std::vector<int> a{6, 10, 14, 20};
  std::vector<int> b{4, 8, 16, 20};

  auto a_size = a.size();

  a.insert(a.end(), b.begin(), b.end());

  // merge point is where `a` and `b` meet: at the end of original `a`.    
  std::inplace_merge(a.begin(), a.begin() + a_size, a.end());

  auto last = std::unique(a.begin(), a.end());
  a.erase(last, a.end());

  for(auto e: a) {
    std::cout << e << ' ';
  }
  std::cout << '\n';
}