我一直在我们的项目上运行Valgrind,并且valgrind报告说,尽管在函数的底部调用了freeaddrinfo,但是从getaddrinfo的调用中已经丢失了内存。知道可能导致这种情况的原因吗?
int tcp_connect(char *address, char *port)
{
//printf("%s\n ", address);
int status, sockfd;
struct addrinfo hints, *servinfo, *p;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype= SOCK_STREAM;
status = getaddrinfo(address,port,&hints,&servinfo);
if(status != 0){
printf("tcpconnect: getaddrinfo failed\n");
}
for(p = servinfo; p != NULL; p = p->ai_next) {
sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if(sockfd == -1){
printf("tcpconnect: socket failed\n");
continue;
}
status = connect(sockfd, p->ai_addr, p->ai_addrlen);
if(status == -1){
close(sockfd);
printf("tcpconnect: connect failed\n");
continue;
}
break;
}
if (p == NULL){
printf("tcpconnect: could not get a valid socket file descriptor\n");
return -1;
}
freeaddrinfo(servinfo);
//return socket
return sockfd;
}
valgrind输出在这里:
==7803== 384 bytes in 8 blocks are definitely lost in loss record 30 of 37
==7803== at 0x4023CC8: malloc (vg_replace_malloc.c:236)
==7803== by 0x413FE46: gaih_inet (in /lib/libc-2.7.so)
==7803== by 0x4141CA1: getaddrinfo (in /lib/libc-2.7.so)
==7803== by 0x804D20D: tcp_connect (tcpconnect.c:18)
==7803== by 0x804D505: update_radio_data_t (radiodata.c:69)
==7803== by 0x4073368: start_thread (in /lib/libpthread-2.7.so)
==7803== by 0x4159CFD: clone (in /lib/libc-2.7.so)
我对此内存泄漏感到困惑,因为我确保在底部调用freeaddrinfo。这可能是Valgrind或freeaddrinfo中的错误吗?
答案 0 :(得分:8)
您的失败路径(if (p == NULL)
)未拨打freeaddrinfo
,我会在检查前将呼叫移至此处。
答案 1 :(得分:4)
if (p == NULL){
printf("tcpconnect: could not get a valid socket file descriptor\n");
return -1;
}
如果此条件为真,则不会调用freeaddrinfo(servinfo)
。