gpt4 book ai didi

c - Linux getgrent() 结果为 "Segmentation fault"

转载 作者:行者123 更新时间:2023-12-04 19:06:35 31 4
gpt4 key购买 nike

我正在尝试打印所有系统组(Ubuntu 20.04):

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <grp.h>

int main(int argc, char *argv[])
{
printf("Here are all of this system's groups:\n\n");

struct group* grp;
while ((grp = getgrent()) != NULL)
puts(grp->gr_name);

endgrent();

exit(EXIT_SUCCESS);
}
我用 sudo 运行程序我得到:
$ sudo ./program
Here are all of this system's groups:

Segmentation fault
使用 struct spwd 时会发生同样的错误.
更新
我用 include 更新了源代码行,我省略了 lib/*.c部分。当我编译这段确切的代码时:
$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:hsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: [...]
Thread model: posix
gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)

$ gcc -std=c17 main.c -o program
main.c: In function ‘main’:
main.c:11:18: warning: implicit declaration of function ‘getgrent’ [-Wimplicit-function-declaration]
11 | while ((grp = getgrent()) != NULL)
| ^~~~~~~~
main.c:11:16: warning: assignment to ‘struct group *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]
11 | while ((grp = getgrent()) != NULL)
| ^
main.c:14:4: warning: implicit declaration of function ‘endgrent’ [-Wimplicit-function-declaration]
14 | endgrent();
| ^~~~~~~~
当我运行它时:
$ ./program 
Here are all of this system's groups:

Segmentation fault (core dumped)

$ sudo ./program
Here are all of this system's groups:

Segmentation fault
现在,当我运行 VS Code 调试器时,它可以正常工作。 VS Code 根据 this article 配置.
这是我的 launch.json :
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "gcc-9 - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: gcc-9 build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}

最佳答案

添加正确的标题:

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <grp.h>

int main(int argc, char *argv[])
{
printf("Here are all of this system's groups:\n\n");

struct group* grp;
while ((grp = getgrent()) != NULL)
puts(grp->gr_name);

endgrent();

exit(EXIT_SUCCESS);
}

更新: -std=c17很奇怪,它没有包含 <grp.h> .您可能需要 std=gnu17 ,其中包括一些 gnu+posix 的东西。

关于c - Linux getgrent() 结果为 "Segmentation fault",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68021820/

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