Getting segmentation fault while initialising nested structure variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Maddy375
    New Member
    • Nov 2014
    • 1

    #1

    Getting segmentation fault while initialising nested structure variable

    Dear Friends,
    I am not able to assign value into struct addrinfo variable through struct sort_result structure variable.
    Code:
    struct addrinfo
    {
       int ai_flags; /* Input flags. */
    
       int ai_family; /* Protocol family for socket. */
    
       int ai_socktype; /* Socket type. */
    
       int ai_protocol; /* Protocol for socket. */
    
       socklen_t ai_addrlen; /* Length of socket address. */
    
       struct sockaddr *ai_addr; /* Socket address for socket. */
    
       char ai_canonname; /* Canonical name for service location. */
    
       struct addrinfo *ai_next; /* Pointer to next in list. */
    };
    
    
    struct sort_result
    {
        struct addrinfo *dest_addr;
    
        /* Using sockaddr_storage is for now overkill. We only support IPv4 and IPv6 so far. If this changes at some point we can adjust the type here. */
    
        struct sockaddr_in6 source_addr;
    
        uint8_t source_addr_len;
    
        bool got_source_addr;
    
        uint8_t source_addr_flags;
    
        uint8_t prefixlen;
    
        uint32_t index;
    
        int32_t native;
    };
    
    int main ()
    {
        struct sort_result a1;
        cout<<"before"<<endl;
    
        memset(&a1, 0, sizeof (struct sort_result));
    
        memset(&a1.dest_addr, 0, sizeof (struct addrinfo));
    
        cout<<"after"<<endl;
        cout<<"Index"<<a1.index<<endl;
    
    /** not able to assign value into struct addrinfo variable through struct sort_result structure variable **/
     here-->>>    a1.dest_addr->ai_family = AF_UNSPEC; 
    
        cout<<"after initialize"<<endl;
        a1.dest_addr->ai_socktype = SOCK_STREAM;
    
        return 0;
    }
    Last edited by Frinavale; Nov 13 '14, 08:33 PM. Reason: Added code tags.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    You never created a struct addrinfo variable. All you did was create a pointer that was never initialized.

    Use malloc to create a memory allocation for sizeof(struct addrinfo) and then assign the address returned by malloc to your struct addrinfo pointer.

    Don't forget that you need to free this memory when you no longer need it to prevent a leak.

    Comment

    Working...