getifaddrs - Memory leak

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kardon33
    New Member
    • May 2007
    • 158

    getifaddrs - Memory leak

    Hello Bytes,

    I am using getifaddrs from ifadddrs.h on Debian Linux (Lenny).

    Im using valgrind to check for memory leaks in my program. It seems that I have a memory leak in the code below but I cant figure out how to fix it. I thought i was freeing the address structure right but no luck.

    If I do not run the loop and call "ifAddrStru ct = ifAddrStruct->ifa_next;" I don't get a memory leak but it also destroys the functionality of my method.

    Any thoughts?

    Code:
    #include <ifaddrs.h> // Used for getting local address
    
        struct ifaddrs * ifAddrStruct = NULL;
        getifaddrs(&ifAddrStruct);
    
        while (ifAddrStruct != NULL) {
    
            if (ifAddrStruct->ifa_addr->sa_family == AF_INET && strcmp(ifAddrStruct->ifa_name, "lo0") != 0) { // check it is IP4 and not lo0
    
            }
            ifAddrStruct = ifAddrStruct->ifa_next;
        }
    
        freeifaddrs(ifAddrStruct);
        ifAddrStruct = NULL;
  • kardon33
    New Member
    • May 2007
    • 158

    #2
    Well i figured it out.

    I had to create a second address structure like:

    Code:
    struct ifaddrs * ipa = NULL;
    Then set ipa equal to ifAddrStruct before using ipa in the while loop.

    This allows the code to keep a copy of linked list head ifAddrStruct for freeing.

    Final Code looks like:

    Code:
    
        struct ifaddrs * ifAddrStruct, *ipa = NULL;
        void * tmpAddrPtr = NULL;
        char s[INET6_ADDRSTRLEN];
    
       
        getifaddrs(&ifAddrStruct);
        localAddress.clear();
    
        ipa =  ifAddrStruct;
        while (ipa != NULL) {
            
            if (ipa->ifa_addr->sa_family == AF_INET && strcmp(ipa->ifa_name, "lo0") != 0) { // check it is IP4 and not lo0
              
                
                // is a valid IP4 Address
                tmpAddrPtr = &((struct sockaddr_in *) ipa->ifa_addr)->sin_addr;
    
                inet_ntop(AF_INET, tmpAddrPtr, s, sizeof (s));
    
    
            }
    
             ipa = ipa->ifa_next;
        }
    
        freeifaddrs(ifAddrStruct);

    Comment

    Working...