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

标签 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;
  }

最佳答案

您重复的字符串可能为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/

相关文章:

c - 动态字符数组

c - 释放下属?

c - realloc:释放对象的无效校验和

c - malloc成功但分配失败

c - 查找同一 block 或数组中指针之间的距离

c - 在 malloc 实现中维护空闲列表

C错误检查函数

在 C 中计算分数指数

c - 在C中强制转换为指针类型时会发生什么情况?

c - 如何连接指针数组?