Strdup正在产生核心转储?

时间:2015-05-08 17:20:10

标签: c malloc

我有一个用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;
  }

1 个答案:

答案 0 :(得分:1)

您复制的字符串可能是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指针的实用程序函数。