gpt4 book ai didi

c - 使用静态变量时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:24:29 25 4
gpt4 key购买 nike

#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));
}

在上面的代码中,当我使用 main 函数时:

printf("%ld\n", (long)(Getpwnam_("root")->pw_uid));
printf("%ld\n", (long)(Getpwnam_("cho")->pw_uid));

运营良好。但是,当我使用一个 printf() 和两个 Getpwnam_() 作为参数时,我得到了一个段错误。我认为我的代码运行没有问题。

但是,为什么这会给我一个段错误??

最佳答案

一个问题是您试图同时保持两个密码条目有效。随后调用 getpwent 可能会覆盖之前返回的信息。所以你需要在再次调用getpwent之前处理完返回的信息。如有必要,复制您需要的字段。

此外,无需将指针声明为静态,因为您不会返回其地址。

(atturri 提到了另一个问题,即您没有在调用之间使用 setpwent 倒回到密码的开头。如果代码检查了NULL 在尝试引用密码字段之前返回。)

关于c - 使用静态变量时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37043815/

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