Search code examples
cnetwork-programmingfree

How does the static allocation of a protoent struct work?


In C, when I use the getprotoent(), getprotobyname() and getprotobynumber() functions from netdb.h, I get a pointer to a "statically allocated protoent structure". So I understand there's no need to free any memory myself.

However, how exactly is that memory allocated? What is its scope? The docs say that these functions "all use the same static area to return the protoent structure", which "is only valid until the next one of these functions is called on the same thread".

Therefore, at what time is that memory freed? That's what I'd really like to be able to fully understand. Thank you very much!


Solution

  • The memory for these static areas is set aside at the time the program start and remains valid for the life of the program.

    Consider this code:

    char *getname(void)
    {
        static char name[] = "my name";
        return name;
    }
    

    The static keyword when applied to a variable inside of a function means it lifetime is that of the full program. This allows you to return a pointer to this variable from the function that is still valid when the function exits. It's effectively a global variable whose name is only visible inside of the function.

    The protoent family of functions do something similar. They internally have a static variable that they populate and return a pointer to.