Linux下正确使用getifaddrs()函数避免内存泄露

来源:互联网 发布:丹尼·格兰杰数据 编辑:程序博客网 时间:2024/05/22 11:32

工作中使用valgrind检测内存泄露时,发现getifaddrs()很容易导致内存泄露,下面是正确的代码:

//get local ip of network card//gcc -g get_addr.c -o get_addr//#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <ifaddrs.h>int main(int argc, char* argv[]){    struct ifaddrs *ifc, *ifc1;    char ip[64] = {};    char nm[64] = {};    if(0 != getifaddrs(&ifc)) return -1;    ifc1 = ifc;    printf("iface\tIP address\tNetmask\n");    for(; NULL != ifc; ifc = (*ifc).ifa_next){        printf("%s", (*ifc).ifa_name);        if(NULL != (*ifc).ifa_addr) {            inet_ntop(AF_INET, &(((struct sockaddr_in*)((*ifc).ifa_addr))->sin_addr), ip, 64);            printf("\t%s", ip);        }else{            printf("\t\t");        }        if(NULL != (*ifc).ifa_netmask){            inet_ntop(AF_INET, &(((struct sockaddr_in*)((*ifc).ifa_netmask))->sin_addr), nm, 64);            printf("\t%s", nm);        }else{            printf("\t\t");        }        printf("\n");    }    //freeifaddrs(ifc);    freeifaddrs(ifc1);    return 0;}
编译方法:

gcc -g get_addr.c -o get_addr

运行和检测如下:


但是如果将末尾的ifc1更改为ifc,就会造成内存泄露, 真正的原因是, ifc不是真正的链表, 仅是伪链表.参见下面的参考文献[1].


参考文献

[1].http://xinzhiwen198941-163-com.iteye.com/blog/994704

[2].http://blog.csdn.net/bailyzheng/article/details/7489656 

0 0