Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happened on freeaddrinfo called?

I'm learning network programming by following the Beej's Guide to Network Programming article. There is an example:

struct addrinfo hints, *servinfo, *p;

if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    return 1;
}

// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
    //socket(...)
    //bind(...)
    break;
}

freeaddrinfo(servinfo); // all done with this structure

if (p == NULL)  {
    fprintf(stderr, "server: failed to bind\n");
    exit(1);
}

After bind(), freeaddrinfo() is called. I think the servinfo link list should be NULL now, and also the pointer p should be NULL, but no, p is not NULL and the code works well.

I want to know why the p is not null after calling freeaddrinfo ?

like image 852
user1418404 Avatar asked Oct 19 '25 14:10

user1418404


1 Answers

After the loop the pointer p either points to the addrinfo structure that was used to successfully create and bind the socket, or it will be NULL if none of the structures could be used.

That the freeaddrinfo was called between the loop and the check doesn't matter, because you don't dereference the variable p, you only check if it's a null-pointer or not.

However, if you try to dereference p after the call to freeaddrinfo then you would try to access memory no longer allocated to you, and you will have undefined behavior.

The freeaddrinfo call doesn't change any of your variables, it can't. If you have a pointer allocated with malloc and then you call free with that variable, it doesn't set the variable to NULL, nor could it set any other variable pointing to the same memory to NULL. Read more about passing argument by value and emulating pass by reference in c to learn more about why.

like image 51
Some programmer dude Avatar answered Oct 21 '25 04:10

Some programmer dude