beejjorgensen/bgnet

May have forgotten to freeaddrinfo in 6.1 A Simple Stream Server

Closed this issue · 1 comments

I'm reading the example program of the section 6.1 of your very instructive guide. I'm not sure but I think that the *servinfo data may be leaked.

It's allocated here:

if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {

And freed here:
freeaddrinfo(servinfo); // all done with this structure

But there is a possibility the program exits before the call to freeaddrinfo():

bgnet/examples/server.c

Lines 74 to 78 in cce225a

if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
sizeof(int)) == -1) {
perror("setsockopt");
exit(1);
}

Shouldn't the linked list be freed in that case too ? Or there is some magic happening that I don't understand/know ?
Another solution might be to continue instead of exit()ing. I don't understand why there is a need to exit().

I'm just getting to this. 😊 The short answer is that all memory allocated to a process is freed when the process exits, so no worries about freeing the thing.
But why exit() there and not continue... I don't really have a good answer, other than that setsockopt() call really shouldn't fail, and if it does, maybe something else is going on. Also, the setsockopt() call isn't necessary; it just helps when a socket isn't cleaned up fully after a crash.
I think I'm going to leave it as-is for the moment, but keep mulling it.