如何正确克隆struct addrinfo

时间:2019-05-20 11:36:28

标签: tcp udp

我需要克隆一个现有的struct addrinfo指针。我已经写了下面的代码来克隆它。认为从功能上讲它可以正常工作,但是当我释放克隆的strutc addrinfo指针时出现内存泄漏。

struct addrinfo * transport_clone_addrinfo(struct addrinfo *src)
{
    struct addrinfo *dst;

    if(src == NULL)
    {
        return NULL;
    }

    dst = calloc(1, sizeof(struct addrinfo));
    dst->ai_next = NULL;

    dst->ai_flags = 0; 
    dst->ai_family = src->ai_family;
    dst->ai_socktype = src->ai_socktype;
    dst->ai_protocol = src->ai_protocol;
    dst->ai_canonname = NULL;
    dst->ai_addrlen = src->ai_addrlen;
    dst->ai_addr = malloc(src->ai_addrlen);
    memcpy(dst->ai_addr, src->ai_addr, src->ai_addrlen);

    return dst;
}

int main(int argc, char **argv)
{
    char *ip = "192.168.1.10";
    unsigned short port = 5555;
    int index;
    int ret_val = -1;
    char service[8];
    struct addrinfo hints;
    struct addrinfo *rp = NULL;
    struct addrinfo *rp2;

    index = sprintf(service, "%u", port);
    service[index] = 0;

    if(true)
    {
        memset(&hints, 0, sizeof(struct addrinfo));
        hints.ai_family = AF_INET;
        ret_val = getaddrinfo(ip, NULL, &hints, &rp);
    }
    else
    {
        ret_val = getaddrinfo(ip, service, NULL, &rp);
    }

    if(ret_val != 0)
    {
        printf("\ngetaddrinfo failed\n");
    }

    rp2 = transport_clone_addrinfo(rp);

    freeaddrinfo(rp);
    freeaddrinfo(rp2);

    return 0;
}

借助此功能,它可以正常工作。但是valgrind报告下面的代码行内存泄漏。

dst->ai_addr = malloc(src->ai_addrlen);

然后,我检查了freeaddrinfo代码,我发现struct addrinfo的ai_addr成员未明确释放。

克隆时可能丢失了一些东西。有人可以帮助我了解如何正确克隆struct addrinfo。

是否有任何C api可以克隆struct addrinfo?

1 个答案:

答案 0 :(得分:0)

实际上,有一个实现getaddrinfo的技巧,它将为rp分配整个内存(sizeof(struct addrinfo)+ ai_addrlen),因此freeaddrinfo只会释放rp和rp.ai_canonname。