gpt4 book ai didi

c - Strdup 正在生成核心转储吗?

转载 作者:行者123 更新时间:2023-11-30 19:16:29 25 4
gpt4 key购买 nike

我有一个用 C 编写的应用程序。我在那里使用 strdup 来复制 char*。在调用 strdup 之前,我正在验证源字符串。即使 strdup 正在转储核心,它也不等于 NULL。

这是回溯

#0  0x0000005564517bb0 in raise () from /lib64/libc.so.6
#1 0x000000556451c4bc in abort () from /lib64/libc.so.6
#2 0x0000005564552b48 in __libc_message () from /lib64/libc.so.6
#3 0x000000556455f024 in malloc_printerr () from /lib64/libc.so.6
#4 0x0000005564562ea4 in _int_malloc () from /lib64/libc.so.6
#5 0x0000005564565638 in malloc () from /lib64/libc.so.6
#6 0x0000005564569748 in strdup () from /lib64/libc.so.6
#7 0x0000000120009804 in read_filesystem_list ()
#8 0x000000012000a7d0 in monitor_disk ()
#9 0x0000005564213660 in start_thread () from /lib64/libpthread.so.0
---Type <return> to continue, or q <return> to quit---
#10 0x00000055645ce5dc in __thread_start () from /lib64/libc.so.6

任何人都可以帮助我理解为什么 strdup 会转储核心吗?

struct abc *read_filesystem_list () 
{
struct abc *me =NULL;
struct abc *list =NULL;
struct abc *temp =NULL;
FILE *fp;
fp = setmntent (table, "r");
while ((mnt = getmntent (fp)))
{
me = (struct abc *) malloc (sizeof (struct abc));
if(me)
{
memset(me, 0, sizeof(struct abc));
if ( mnt->mnt_dir != NULL && mnt->mnt_fsname !=NULL && org_devname!= NULL&& mnt->mnt_type != NULL )
{
me->devname = strdup (mnt->mnt_fsname);
me->org_devname = strdup(org_devname);
me->mp = strdup (mnt->mnt_dir);
me->type = strdup (mnt->mnt_type);
}
if(temp) {
temp->next = me;
temp = me;
}
else {
list=temp=me;
}
}
}
return list;
}

最佳答案

您重复的字符串可能为NULL:

if ( mnt->mnt_dir != NULL || mnt->mnt_fsname != NULL )
{
me->devname = strdup (mnt->mnt_fsname);
me->org_devname = strdup(org_devname);
me->mp = strdup (mnt->mnt_dir);
me->type = strdup (mnt->mnt_type);
}
}

您的测试不正确且不完整。这样效果会更好:

if (mnt->mnt_fsname) me->devname = strdup(mnt->mnt_fsname);
if (org_devname) me->org_devname = strdup(org_devname);
if (mnt->mnt_dir) me->mp = strdup(mnt->mnt_dir);
if (mnt->mnt_type) me->type = strdup(mnt->mnt_type);

您还可以编写一个实用函数来复制字符串并接受 NULL 指针。

关于c - Strdup 正在生成核心转储吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30129422/

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