c - getpwnam 的奇怪行为

标签 c linux static-variables getpwuid getpwnam

#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
        printf("%s %s\n", getpwnam("steve")->pw_name, getpwnam("root")->pw_name);
        printf("%d %d\n", getpwnam("steve")->pw_uid, getpwnam("root")->pw_uid);

        return EXIT_SUCCESS;
}
$ gcc main.c && ./a.out
steve steve
1000 0

8 行中,我们尝试打印用户名 steve 和 root,但它打印了两次 steve。在 9 行,我们尝试打印 steve 和 root 的 UID,它成功打印了它们。

我想确定 8 行中那个奇怪行为的根本原因。

我知道getpwnam返回的指针指向静态分配的内存,pw_name/pw_passwd/pw_gecos/pw_dir/pw_shell等字段指向的内存也是静态的,这意味着这些值可以被后续调用覆盖。但对这个奇怪的结果还是一头雾水。

This is exercise 8-1 of The Linux Programming Interface. Add this so that someone like me could find this through the search engine in the future:). And the question in the book is wrong, go here to see the revised version.

最佳答案

代码连续调用 getpwnam() 返回一个指向同一地址的指针,并将同一指针传递给 printf() 两次。编译器决定进行调用的顺序将决定它是显示“steve”还是“root”。

通过调用 getpwnam_r() 分配两个缓冲区空间并在对 printf() 的调用中分别使用一个缓冲区空间相反。

关于c - getpwnam 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73452740/

相关文章:

c - C 中结构数组的 'sizeof' 结果?

c++ - 错误 : pasting "tmp_UINT" and "+" does not give a valid preprocessing token

c# - 在 Linux 中使用 C# Mono 控制并口

c - 尝试从 printf 语句中的函数打印静态变量时出现奇怪的输出

c - 为什么静态变量在每次调用函数时都会初始化,但在 C 中每次都必须声明它

python - 从静态方法访问静态变量

c - 下面的类型转换 c 代码有什么问题

c - 我如何限制以十进制显示的二进制到二进制转换器?

c++ - 获取整数位集中前导 1 位置的最快方法?

linux - 在我的 bash 脚本中获取 "syntax error near unexpected token ` fi'"