#include <pwd.h>
#include <stdio.h>
struct passwd* Getpwnam_(const char* name)
{
static struct passwd* passwd;
while((passwd=getpwent())!=NULL) /* get pw entry line by line */
{
if(strcmp(passwd->pw_name, name)==0) /* find the same name */
return passwd;
}
if(passwd==NULL) /* there is no matching name */
return NULL;
}
int
main(void)
{
printf("%ld %ld\n", (long)(Getpwnam_("root")->pw_uid), (long)(Getpwnam_("cho")->pw_uid));
}
On the above code, when I use main functions like:
printf("%ld\n", (long)(Getpwnam_("root")->pw_uid));
printf("%ld\n", (long)(Getpwnam_("cho")->pw_uid));
It is well operated. But, when I use one printf() with two Getpwnam_() as arguments, I get a segmentation fault. I think there's no problem in my code operation.
But, why this gives me an segmentation fault??
choexisst on your system?0 \n 1000when I use command below one, not above one` and I'm using root account.return. In practice, the only reason for escaping the loop is covered by theifcondition, so it always returns a value, but the test is unnecessary and removing the test avoids having the compiler complain.