Will gethostbyname_r leak memory if pointers in hostent are not freed?

The prototype gethostbyname_r

is:

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

      

To avoid non-reentry gethostbyname

, I wrote these materials:

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

      

This is quite similar to the example in the GNU doc , as well as the implementation in eglibc-2.15 for gethostname

.

But I have noticed that struct hostent

there is h_name

, h_aliases

, h_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 */
}

      

So I'm wondering if it's really not important to free the content that these pointers are referring to. Is there another mechanism for processing these memories?

+3


source to share


1 answer


You have to print out the values โ€‹โ€‹of the pointers in this structure to find out the answer to your question. You will find that they all point to data within the buffer you allocated.

So everything free

is all you need to free up all memory.



But that also means that you shouldn't release that allocation until you've finished using or copying any data that interests you. You're releasing your code too early.

+5


source







All Articles