gpt4 book ai didi

c - 此 netbsd 代码是否可重入

转载 作者:行者123 更新时间:2023-11-30 14:23:49 25 4
gpt4 key购买 nike

我正在通过阅读 NetBSD 源代码来学习“阅读代码”。
(有兴趣的可以看阅读:开源视角>我在读)



我发现了这个功能:



/* convert IP address to a string, but not into a single buffer
*/
char *
naddr_ntoa(naddr a)
{
#define NUM_BUFS 4
static int bufno;
static struct {
char str[16]; /* xxx.xxx.xxx.xxx\0 */
} bufs[NUM_BUFS];
char *s;
struct in_addr addr;

addr.s_addr = a;
strlcpy(bufs[bufno].str, inet_ntoa(addr), sizeof(bufs[bufno].str));
s = bufs[bufno].str;
bufno = (bufno+1) % NUM_BUFS;
return s;
#undef NUM_BUFS
}

由于 inet_ntoa 不可重入,因此它引入了 4 个不同的临时缓冲区来包装 inet_ntoa 函数。
但在我看来,这个 naddr_ntoa 函数也是不可重入的:
静态 bufno 变量可以由其他变量操作,因此临时缓冲区在这里似乎无法按预期工作。

那么这是一个潜在的错误吗?

最佳答案

是的,这是一个潜在的错误。如果您想要一个很可能可重入的类似函数,您可以使用例如inet_ntop (顺便也处理 IPv6)。

关于c - 此 netbsd 代码是否可重入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12506875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com