Question

I started some socket programming, and I ran across the function inet_ntoa . The function has the prototype char * inet_ntoa(struct in_addr in);.

So how/where will this string be allocated? Am I expected to call free on it?

Was it helpful?

Solution

From inet_ntoa(3):

The inet_ntoa() function converts the Internet host address in given in network byte order to a string in standard numbers-and-dots notation. The string is returned in a statically allocated buffer, which subsequent calls will overwrite

So, no.

OTHER TIPS

No, you don't free it. It's usually static storage within the function, or thread-specific data if you're running in a threaded environment.

From the definitive POSIX man page:

The return value of inet_ntoa() may point to static data that may be overwritten by subsequent calls to inet_ntoa().

That page also states:

The inet_ntoa() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe.

That means that, even in a threaded environment, it may not be thread-safe at all.

In other words, it can be implemented something like:

char *inet_ntoa (struct in_addr xyz) {
    static char buff[50];
    // Do something with xyz to populate buff.
    return buff;
}

You don't need to free it since it is static.

But you have to take a copy of the string contents before you call the function again, otherwise you'll overwrite the contents from the first call.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top