gpt4 book ai didi

c - 如何正确调试用 C 编写的共享库?

转载 作者:太空狗 更新时间:2023-10-29 11:06:45 24 4
gpt4 key购买 nike

我目前正在编写一个共享库,它接受一个 UNIX 用户名并返回一个字符串,其中包含该用户在 [group1, group2, group3...] 中所属的所有组。格式。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <utmp.h>
#include <sys/types.h>
#include <grp.h>
#include <pwd.h>

int num_groups = 0;
struct passwd *pwd;
gid_t *groups;
struct group *grp;

FILE *stream;
char *buff;
size_t length;

char *printGroups(char *arg)
{
stream = open_memstream(&buff, &length);
pwd = getpwnam(arg);
getgrouplist(arg, pwd->pw_gid, groups, &num_groups);
groups = malloc(num_groups * sizeof(gid_t));
if (groups == NULL){
perror("malloc");
exit(EXIT_FAILURE);
}
getgrouplist(arg, pwd->pw_gid, groups, &num_groups);
fprintf(stream, " [");
for (int i = 0; i < num_groups; ++i){
grp = getgrgid(groups[i]);
if (i == num_groups - 1)
fprintf(stream, "%s", grp->gr_name);
else
fprintf(stream, "%s ", grp->gr_name);
}
free(groups);
fprintf(stream, "]");
fclose(stream);
return buff;
}

这是我的共享库中返回字符串的主要函数。我验证了该函数确实是正确的——相同的逻辑在使用 printf 而不是 open_memstream 的独立程序中起作用。字符串流。

但是库会出现段错误,我无法查明原因。 Valgrind 不输出任何有用的东西:

gcc -shared -fpic -g -Wall lib.c
valgrind ./a.out
==9916== Process terminating with default action of signal 11 (SIGSEGV)
==9916== Access not within mapped region at address 0x0
==9916== at 0x1: ???
==9916== by 0xFFF000672: ???

gdb 回溯也是如此:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000001 in ?? () (gdb) backtrace
#0 0x0000000000000001 in ?? ()
#1 0x00007fffffffe6e9 in ?? ()
#2 0x0000000000000000 in ?? ()

我没有想法。有人能给我指出一个解决方案,例如 .so 源中的错误或 Valgrind 和 gdb 都打印的原因吗???尽管在编译时使用了 -g 标志?

最佳答案

看起来您正在尝试直接运行共享库。这不是共享库的工作方式。它们被使用它们的其他程序引用。

例如,此代码将使用您的库:

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

char *printGroups(char *);

int main()
{
char *groups = printGroups("root");
printf("groups: %s\n", groups);
free(groups);
return 0;
}

如果您首先像这样编译您的库:

gcc -shared -fpic -g -Wall lib.c -o libmylib.so

然后,假设这个库与上面的测试代码位于同一目录中,您可以像这样编译测试代码:

gcc -g -Wall -Wextra -L. -o mytest mytest.c -lmylib

然后设置一个环境变量来查找你的库:

export LD_LIBRARY_PATH=.

然后您可以运行将使用您的库的测试程序。

关于c - 如何正确调试用 C 编写的共享库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55088193/

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