2013-11-04 54 views
0

最近,我通过编写不同的数据结构来提高编程技能,而这正是开始!链接列表操作(核心转储)

现在我正在写链表,但有些恼人的事情发生了,麻烦已经很长时间让我很烦恼,因为我对这个错误不太确定, 分段错误(核心转储),但我确实知道我在内存操作上做错了。

link_list.h:

struct LINK_LIST { 
    char *string; 
    struct LINK_LIST *next; 
}link_list; 

==============================

link_list .C:

#include<stdio.h> 
#include<stdlib.h> 

int init_link_list(struct LINK_LIST *new_link) { 
    //char *new_string; 
    int i; 
    //new_string = (char *)malloc(sizeof(char) * STRING_SIZE); 
    new_link = (struct LINK_LIST *)malloc(sizeof(struct LINK_LIST)); 
    if (new_link==NULL) { 
fprintf(stderr, "Insufficient memory!!!"); 
return ERROR; 
    } 
    //new_link->string = new_string; 
    new_link->string = NULL; 
    //new_link->next = NULL; 

    return OK; 
} 

在这里,我自己定义的init操作,那么插入操作:

int insert(struct LINK_LIST *link, int pos, char *in) { 
    int i; 
    if (get_length(link)>=STRING_SIZE) { 
    fprintf(stderr, "Link list is full!!!"); 
    return ERROR; 
    } 
    else { 
    if (pos < 0 || pos-1 > get_length(link)) { 
     fprintf(stderr, "Invalid position"); 
     return ERROR; 
    } 
    else { 
     i = 0; 
     do { 
      struct LINK_LIST *new_node; 
      init_link_list(new_node); 
      new_node->next = link->next; 
      link->next = new_node; 
      new_node->string = in; 
      i += 1; 
     } while(i<pos-1); 
    } 
} 
return OK; 
} 
+0

您的第一份工作是删除在'='右侧的'(struct LINK_LIST *)'投射。 – Bathsheba

+0

您需要遵循以下准则:http://sscce.org/发布您可以制作的最小的失败测试用例。 –

+0

'init_link_list(new_node);'之后,指针'new_node'仍未初始化。 – aschepler

回答

2

你具有有一个错误:

struct LINK_LIST *new_node; 
init_link_list(new_node); 

init_link_list,该参数的值被修改:

new_link = (struct LINK_LIST *)malloc(sizeof(struct LINK_LIST)); 

但该修改仅是本地的功能;一旦你回到你的通话功能,即更改将丢失:

struct LINK_LIST *new_node; 
init_link_list(new_node); 
// Oops ! new_node's new value is lost ! 

您有内存泄漏(对malloc的结果会丢失),并new_node未初始化。当您尝试访问*new_node时,您将访问内存中的随机位置,从而核心转储。

有几个可能的修正,最简单的就是放弃你的OK/ERROR返回值和返回一个非空指针的malloc成功,或NULL,如果它失败:

struct LINK_LIST *init_link_list(void) { 
    struct LINK_LIST *new_link = malloc(sizeof(struct LINK_LIST)); 

    if (new_link==NULL) { 
    fprintf(stderr, "Insufficient memory!!!"); 
    return NULL; 
    } 

    new_link->next = NULL; 
    return new_link; 
} 

然后,代码插入成为:

... 
else { 
    i = 0; 
    do { 
     struct LINK_LIST *new_node = init_link_list(); 
     // Note : here, should check whether new_node is NULL and deal with the situation 
     new_node->next = link->next; 
     link->next = new_node; 
... 
+0

请给出一个完整的代码让我们分享? – jacouh

+0

但new_link被重新声明! – hyaocuk

+0

@hyaocuk,no,'new_link'不重新声明; 'insert'中的那个和'init_link_list'中的不一样。它们碰巧有相同的名称,但这是巧合的(如果这对您有帮助,您可以将它重命名为2个函数中的任何一个)。我在我的答案中添加了调用新版本'init_link_list'的代码;我希望这有助于理解这一点。 – Fabien