Why inet_ntoa is designed to be a non-reentrant function?

半世苍凉 提交于 2020-01-12 07:48:11

问题


Glancing at the source code of GNU C Library,I found the inet_ntoa is implementated with

static __thread char buffer[18]

My question is, since there is a need to use reeentrant inet_ntoa,why do not the author of GNU C Library use malloc to implementate it?

thanks.


回答1:


The reason it's not using the heap is to conform with standards (POSIX) and other systems. The interface is just not such that you are supposed to free the buffer returned. It assumes static storage..

But by declaring it as thread local (with __thread), two threads do not conflict with each other if they happen to both be calling the function. This is glibc's workaround for the brokenness of the interface.

It's true that this is not re-entrant or consistent with the spirit of that term. If you have a recursive function that calls it, you cannot rely on the buffer being the same between calls. But it can be used by multiple threads, which often is good enough.

EDIT: By the way, I just remembered, there is a newer version of this function that uses a caller-provided buffer. See inet_ntop().



来源:https://stackoverflow.com/questions/1705885/why-inet-ntoa-is-designed-to-be-a-non-reentrant-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!