i有一个应用程序。我正在使用 strdup
复制char*。在调用strdup之前,我正在验证源字符串。即使strdup倾倒了核心,它也不等于空。
这是背面跟踪
#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
指针的实用程序功能。