c - 如果 hostent 中的指针没有被释放,gethostbyname_r 会泄漏内存吗?

标签 c linux networking posix gethostbyaddr

gethostbyname_r的原型(prototype)是:

int gethostbyname_r(const char *name,
    struct hostent *ret, char *buf, size_t buflen,
    struct hostent **result, int *h_errnop);

为了避免不可重入的 gethostbyname,我写了这些东西:

int host2addr(const char *host, struct in_addr *addr) {
    struct hostent he, *result;
    int herr, ret, bufsz = 512;
    char *buff = NULL;
    do {
        char *new_buff = (char *)realloc(buff, bufsz);
        if (new_buff == NULL) {
            free(buff);
            return ENOMEM;
        }   
        buff = new_buff;
        ret = gethostbyname_r(host, &he, buff, bufsz, &result, &herr);
        bufsz *= 2;
    } while (ret == ERANGE);

    if (ret == 0 && result != NULL) 
        *addr = *(struct in_addr *)he.h_addr;
    else if (result != &he) 
        ret = herr;
    free(buff);
    return ret;
}

这与 GNU document 中的示例非常相似以及 gethostname 在 eglibc-2.15 中的实现。

但我注意到,struct hostent 中有h_nameh_aliasesh_addr_list:

struct hostent {
   char  *h_name;            /* official name of host */
   char **h_aliases;         /* alias list */
   int    h_addrtype;        /* host address type */
   int    h_length;          /* length of address */
   char **h_addr_list;       /* list of addresses */
}

因此我想知道不释放那些指针所指的内容是否真的无关紧要。是否有其他机制处理这些内存?

最佳答案

您应该打印出该结构中指针的值,以找出问题的答案。您会发现它们都指向您分配的缓冲区内的数据。

因此,您只需要一个free 就可以释放所有内存。

但是这也意味着在您完成使用或复制您感兴趣的任何数据之前,您不得释放该分配。您在代码中释放得太早了。

关于c - 如果 hostent 中的指针没有被释放,gethostbyname_r 会泄漏内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14539077/

相关文章:

python - 微软 Azure : obtaining public IP on Linux with azure API for Python

PHP套接字连接优化

c++ - Linux - 限制每个进程的线程数

c++ - 如何将 Qt 库连接到标准 C++ 项目?

c# - 给定服务器的 IP 地址和端口,如何使用 C# 测试到服务器的 TCP 连接?

c - 将 SDL 1.2 的默认调色板与 SDL_CreateRGBSurface() 相匹配吗?

linux - 在 Linux 中通过蓝牙访问 Neurosky Mindset 的串行数据

c - 栈内存读取

c - 每次我右键单击鼠标时都会调用 opengl 菜单

c - 这个程序有内存泄漏吗?