struct segfault结构

时间:2014-10-22 23:38:16

标签: c++

我正在尝试为数据包创建一个结构并将ip_header和udp_header放入其中,但是当它到达代码的那一部分时会出现段错误。我已经坚持了很长一段时间而且很难过。

/* IP header struct */
struct ip_header{
    unsigned char       iph_ihl:5, iph_ver:4;
    unsigned char       iph_tos;
    unsigned short int  iph_len;
    unsigned short int  iph_ident;
    unsigned char       iph_flag;
    unsigned short int  iph_offset;
    unsigned char       iph_ttl;
    unsigned char       iph_protocol;
    unsigned short int  iph_chksum;
    unsigned int        iph_sourceip;
    unsigned int        iph_destip; 
};

/*UDP header struct */
struct udp_header{
    unsigned short int udph_srcport;
    unsigned short int udph_destport;
    unsigned short int udph_len;
    unsigned short int udph_chksum;
};

/* Packet struct */
struct packet{
    ip_header ip_hdr;
    udp_header udp_hdr;
    string buffer;
};

int main( int argc, char **argv )
{
    string ip_line;
    string message_line;
    get_input( ip_line, message_line );

ip_header i = create_ip_header( address, ip_line );
udp_header u = create_udp_header();

cout << "IP len\t" << i.iph_len << endl;
cout << "UDP len\t" << u.udph_len << endl;

packet *pkt = ( struct packet* )(i.iph_len + u.udph_len + sizeof( message_line ));


//SEGFAULTS HERE
pkt->ip_hdr = i;
pkt->udp_hdr = u;
pkt->buffer = message_line;

1 个答案:

答案 0 :(得分:1)

这一行错了:

packet *pkt = ( struct packet* )(i.iph_len + u.udph_len + sizeof( message_line ));

您不能将指针设置为一堆长度和大小的总和,它需要指向已分配的对象。它应该是:

packet *pkt = new packet;