开发者

Where are strings returned from functions in libc allocated?

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 al开发者_运维知识库located? Am I expected to call free on it?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜