Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valgrind reporting that getaddrinfo is leaking memory?

I've been running Valgrind on our project, and valgrind has been reporting that memory had been lost from a call to getaddrinfo, despite freeaddrinfo having been called at the bottom of the function. Any idea what might be causing this?

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;
}

The valgrind output is here:

==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)

I'm confused by this memory leak, because I made sure to make the call to freeaddrinfo at the bottom. Could this possibly be a bug in Valgrind or freeaddrinfo?

like image 604
HD_Mouse Avatar asked Dec 16 '22 11:12

HD_Mouse


2 Answers

Your failure path (if (p == NULL)) doesn't call freeaddrinfo, I'd move the call to before the check.

like image 96
Hasturkun Avatar answered Dec 30 '22 09:12

Hasturkun


if (p == NULL){
    printf("tcpconnect: could not get a valid socket file descriptor\n");
    return -1;
}

If this condition is ever true, freeaddrinfo(servinfo) will not be called.

like image 42
Aasmund Eldhuset Avatar answered Dec 30 '22 10:12

Aasmund Eldhuset