使用strdup在C中复制链表

时间:2016-12-04 22:26:59

标签: c

我有一个链接数据结构,我想复制并保存原始链接。所以我可以编辑原始链接列表而不影响复制的链表。我尝试了以下方法,我得到了分段错误。

struct link {
        char * name;
        struct link *next; 
    };


struct list{
        struct link  *first;
        struct link *last; 
    };



 struct list *list_new(){
    struct list *n = calloc(1, sizeof(struct list)); 
    return n; 
};




struct list* copyList(struct list*list){
     struct list*new = list_new(); 
     struct link *current = list -> first;
     struct link *newCurrent = new -> first; 
     struct link *p;
      if(current == NULL)
        return NULL; 


      newCurrent = malloc(sizeof(struct link));
      newCurrent = p;

      while (current != NULL) {
        p ->name = strdup((char*)current -> name); 
        p->next = malloc(sizeof(struct link));
        p = p->next;
        current = current->next;
      }

      return new;
    }

2 个答案:

答案 0 :(得分:0)

我想你想要这样的东西:

struct list *copyList(struct list *list)
{
    struct list *new = list_new(); 
    struct link *current = list->first;
    struct link *newCurrent = malloc(sizeof(struct link));

    if((current == NULL) || (newCurrent == NULL) || (new == NULL))
    {
        if(newCurrent != NULL)
        {
            free(newCurrent);
        }
        if(new != NULL)
        {
            free(new);
        }

        return NULL; 
    }
    else
    {
        new->first = newCurrent; 
    }


    while(current != NULL) 
    {
        newCurrent->name = strdup((char*)current -> name); 
        current = current->next;        
        if(current != NULL)
        {
            newCurrent->next = malloc(sizeof(struct link));
            newCurrent = newCurrent->next;
        }
        else
        {
            newCurrent->next = NULL;
            new->last = newCurrent;
        }
    }

    return new;
}

答案 1 :(得分:0)

copyList()中的错误是:

  •       if(current == NULL)
        return NULL; 
    

    应该允许空列表;以上内容无法返回空列表副本。

  •       newCurrent = malloc(sizeof(struct link));
      newCurrent = p;
    

    正如BLUEPIXY写道:分配然后用uninitialize变量覆盖。此外,上面是浪费,因为malloc()循环中有另一个while

    < / LI>
  • p循环中使用while的未定义值。

已更正(仍未进行分配错误检查):

struct list *copyList(struct list *list)
{
    struct list *new = list_new(); 
    struct link *current = list->first;
    struct link *newCurrent = NULL; 
    struct link **p = &new->first;  // where to place pointer to new node
    for (; current; current = current->next, p = &newCurrent->next)
    {
        newCurrent = *p = malloc(sizeof **p);
        newCurrent->name = strdup(current->name);
    }
    *p = NULL;
    new->last = newCurrent;
    return new;
}