2015-05-20 106 views
0

我想写一个函数,可以添加新的结构到链表的末尾。而它总是出现分段错误。C:链接列表推段错误

void 
push(stk_t *stklist, info_t *gds) 
{ 
    stk_t *current = stklist; 

    if (current == NULL) 
    { 
     current->gds = (info_t *)malloc(sizeof(info_t)); 
     current->gds = gds; 
     current->next = (stk_t *)malloc(sizeof(stk_t)); 
     current->next = NULL; 
    } 
    else 
    { 
     while (current != NULL) 
     { 
      current = current->next; 
     } 
     current->next = (stk_t *)malloc(sizeof(stk_t)); 
     current->next->gds = (info_t *)malloc(sizeof(info_t)); 
     current->next->gds = gds; 
     current->next->next = (stk_t *)malloc(sizeof(stk_t)); 
     current->next->next = NULL; 
    } 

} 

我的结构

typedef struct{ 
    char name[NAME_SIZE]; 
    char aisle; 
    int shelf; 
    int weight; 
    int price; 
    int quantity; 
} info_t; 


typedef struct stk stk_t; 

struct stk{ 
    info_t *gds; 
    stk_t *next; 
}; 

功能推的目的()是第二个参数添加到链接列表的末尾。

+1

提示:当你做'电流 - > GDS =(info_t *)malloc(sizeof(info_t));','current'具有什么值? – molbdnilo

+3

'if(current == NULL) { current-> gds' - 解引用NULL指针。 – szczurcio

+0

@molbdnilo糟糕,我打破了你的暗示。当我发布时没有看到它,对不起。 – szczurcio

回答

2

您的代码push()是非常错误的。

gds分配,并立即覆盖:

current->gds = (info_t *)malloc(sizeof(info_t)); 
    current->gds = gds; 

即使currentNULL,将立即取消引用(这是最有可能导致分段故障):

if (current == NULL) 
{ 
    current->gds = (info_t *)malloc(sizeof(info_t)); 

另外,不要明确地转换结果malloc


如果我明白你想要做什么,推应该看起来像这样。

void 
push(stk_t **stklist, info_t *gds) 
{ 
    stk_t* current = *stklist; 

    // Create & initialize new entry 
    // gds is passed as parameter, so use it! 
    stk_t* newstk = malloc(sizeof(stk_t)); 
    newstk->gds = gds; 
    newstk->next = NULL; 

    // No entries had been inserted, overwrite root pointer 
    if(current == NULL) { 
     *stklist = newstk; 
     return; 
    } 

    // Find last entry that has available ->next 
    while(current->next != NULL) 
     current = current->next; 

    current->next = newstk; 
} 

... 

// Use it like this 
stk_t* root = NULL; 
push(&root, ...); 
push(&root, ...); 
push(&root, ...); 

这是非常地道 - 保持指针的第一入口,并为第一个条目覆盖指针本身,后者进入最后一个条目,它覆盖next。顺便说一句,这不是,但简单单链表

对于堆栈实施,将是这样的:

void 
push(stk_t **stklist, info_t *gds) 
{ 
    stk_t* newstk = malloc(sizeof(stk_t)); 
    newstk->gds = gds; 
    newstk->next = *stklist; 

    // Push new entry on top of the stack 
    *stklist = newstk; 
} 

info_t* 
pop(stk_t **stklist) { 
    stk_t* current = *stklist; 
    info_t* gds; 

    if(!current) 
     return NULL; 

    // Remove entry from top of the stack and 
    // use next entry as new top 
    *stklist = current->next; 
    gds = current->gds; 
    free(current); 

    return gds; 
} 
+0

thx很多,问题修复。 –