the usage of getaddrinfo()

Hello, in APUE (Advanced Programming in the UNIX Environment), P559, Figure 16.8, appears the following code:

int
main(int argc, char *argv[])
{
struct addrinfo *ailist, *aip;
struct addrinfo hint;
struct sockaddr_in *sinp;
const char *addr;
int err;
char abuf[INET_ADDRSTRLEN];

if (argc != 3)
err_quit("usage: %s nodename service", argv[0]);
hint.ai_flags = AI_CANONNAME;
hint.ai_family = 0;
hint.ai_socktype = 0;
hint.ai_protocol = 0;
hint.ai_addrlen = 0;
hint.ai_canonname = NULL;
hint.ai_addr = NULL;
hint.ai_next = NULL;
if ((err = getaddrinfo(argv[1], argv[2], &hint, &ailist)) != 0)
err_quit("getaddrinfo error: %s", gai_strerror(err));
for (aip = ailist; aip != NULL; aip = aip->ai_next) {
print_flags(aip), printf("\t");
print_family(aip), printf("\t");
print_type(aip), printf("\t");
print_protocol(aip), printf("\t");
printf("\n host: \t%s", aip->ai_canonname?aip->ai_canonname:"-");
if (aip->ai_family == AF_INET) {
sinp = (struct sockaddr_in *)aip->ai_addr;
addr = inet_ntop(AF_INET, &sinp->sin_addr, abuf,
INET_ADDRSTRLEN);
printf("\n address:\t%s", addr?addr:"unknown"), printf("\t");
printf("\n port:\t%d", ntohs(sinp->sin_port)), printf("\t");
}
printf("\n");
}
exit(0);
}

Now there is a question:
In the example, it declares struct addrinfo *ailist, *aip;
And ailist is used in a for loop:
for (aip = ailist; aip != NULL; aip = aip->ai_next) {
...
printf("\n host: \t%s", aip->ai_canonname?aip->ai_canonname:"-");
...
}
But where is the memory aip pointer to, in the for loop?
Does it call malloc to allocate memory for the list of struct addrinfo?
If so, in the example, it doesn't call freeaddrinfo() to free the allocated memory, and so does in the later examples, which is thought to cause memory leakage.
Can anyone help me?
closed account (DSLq5Di1)
Memory is allocated in the call to getaddrinfo, ailist is assigned the address of that allocated memory, and aip is a copy of ailist. When no longer needed that memory should be freed!

http://msdn.microsoft.com/en-us/library/ms738520#freeing_address_information_from_dynamic_allocation
Topic archived. No new replies allowed.