Linux下正确使用getifaddrs()函数避免内存泄露
生活随笔
收集整理的這篇文章主要介紹了
Linux下正确使用getifaddrs()函数避免内存泄露
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
工作中使用valgrind檢測內(nèi)存泄露時(shí),發(fā)現(xiàn)getifaddrs()很容易導(dǎo)致內(nèi)存泄露,下面是正確的代碼:
//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
運(yùn)行和檢測如下:
但是如果將末尾的ifc1更改為ifc,就會(huì)造成內(nèi)存泄露, 真正的原因是, ifc不是真正的鏈表, 僅是偽鏈表.參見下面的參考文獻(xiàn)[1].
參考文獻(xiàn)
[1].http://xinzhiwen198941-163-com.iteye.com/blog/994704
[2].http://blog.csdn.net/bailyzheng/article/details/7489656?
總結(jié)
以上是生活随笔為你收集整理的Linux下正确使用getifaddrs()函数避免内存泄露的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在Ubuntu 14.04 64bit上
- 下一篇: 在CentOS 6.3 64bit上安装