fel*_*021 3 c linux networking posix gethostbyaddr
原型gethostbyname_r是:
int gethostbyname_r(const char *name,
struct hostent *ret, char *buf, size_t buflen,
struct hostent **result, int *h_errnop);
Run Code Online (Sandbox Code Playgroud)
为了避免不可重入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;
}
Run Code Online (Sandbox Code Playgroud)
这与GNU文档中的示例以及eglibc-2.15中的实现非常相似gethostname.
但是我注意到,有h_name,h_aliases,h_addr_list在struct hostent:
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 */
}
Run Code Online (Sandbox Code Playgroud)
因此,我想知道如果不释放那些指针引用的内容真的无关紧要.是否有其他机制处理这些记忆?
您应该打印出该结构中指针的值,以找出问题的答案.您会发现它们都指向您分配的缓冲区内的数据.
所以free你需要一个单独释放所有内存.
但这也意味着在完成使用或复制您感兴趣的任何数据之前,您不能释放该分配.您的代码过早释放.
| 归档时间: |
|
| 查看次数: |
1434 次 |
| 最近记录: |