Why is getpwnam() always returning root information in a function?

1.1k views Asked by At

I wrote a simple program that calls getpwnam() on a username, passes that username to a function, and then calls getpwnam() again. For some reason, I always get the passwd information for root inside the function.

#include <sys/types.h>
#include <pwd.h>
#include <stdio.h>

void printuser(char *username) {
  printf("USERNAME2: %s\n", username);
  struct passwd *user_info = getpwnam(username);
  printf("USERNAME3: %s\n", username);
  printf("USERNAME4: %s\n", user_info->pw_name);
}

int main(int argc, char *argv[]) {
  struct passwd *user_info = getpwnam(argv[1]);
  printf("USERNAME1: %s\n", user_info->pw_name);
  printuser(user_info->pw_name);
  printf("USERNAME5: %s\n", user_info->pw_name);
}

The program always produces the following output:

$ ./test_getpwnam chenxiaolong
USERNAME1: chenxiaolong
USERNAME2: chenxiaolong
USERNAME3: root
USERNAME4: root
USERNAME5: root

I can't find anything in the man page related to this. Is there something I'm doing wrong?

Thanks in advance!

1

There are 1 answers

1
R.. GitHub STOP HELPING ICE On BEST ANSWER

The return value may point to a static area which is overwritten by a subsequent call to getpwent(), getpwnam(), or getpwuid().

http://pubs.opengroup.org/onlinepubs/9699919799/functions/getpwnam.html

In particular, there is no guarantee about the ordering of reads/writes, so it is not safe to pass data returned from getpwnam back to getpwnam.

You really should not use getpwnam at all; use getpwnam_r instead.