在 C 中将节点添加到链表的末尾会导致堆栈转储

Adding Node to End of Linked List in C causes Stack Dump

我正在尝试将节点添加到链表的末尾,但我收到了 cygwin_exception::open_stackdumpfile。

我的节点结构的定义:

struct Node
{
int number;        /* data portion    */
struct Node *next; /* pointer portion */
};

自由记忆功能:

void free_list(struct Node *list) {
while(list) {
    struct Node *temp = list->next; 
    free(list); 
    list = temp; 
}

}

将节点添加到结束函数:

void add_back(struct Node **list, int value) {
struct Node *node; 
struct Node *temp; 
node = (struct Node*)malloc(sizeof(struct Node)); 

if(node == NULL) {
    printf("Unable to allocate memory."); 
} else {
    node->number = value; 
    node->next = NULL; 

    temp = *list; 

    while(temp->next != NULL) {
        temp = temp->next; 
    }

    temp->next = node; 
}

}

最后但同样重要的是,我对上述功能的测试用例:

void test_add_back(void)
{
int i;
struct Node *list = NULL;

for (i = 1; i <= 10; i++)
{
printf("add %2i to back: ", i);
add_back(&list, i);
print_list(list);
}

free_list(list);
}

反对我的堆栈转储,我应该得到:

test_add_back ========================================
add  1 to back:   1
add  2 to back:   1  2
add  3 to back:   1  2  3
add  4 to back:   1  2  3  4
add  5 to back:   1  2  3  4  5
add  6 to back:   1  2  3  4  5  6
add  7 to back:   1  2  3  4  5  6  7
add  8 to back:   1  2  3  4  5  6  7  8
add  9 to back:   1  2  3  4  5  6  7  8  9
add 10 to back:   1  2  3  4  5  6  7  8  9 10

简而言之,我不确定是哪一块导致了这个堆栈转储,我相当有信心这可能是我的 add_back() 函数中的一个错误,但也有可能是我的 free_list () 函数导致内存泄漏。

无论如何,如果您能帮助确定导致堆栈转储的原因,我们将不胜感激。 干杯, 托比

删除链表中的所有节点后指向头节点的指针等于NULL是可取的。

所以最好定义函数 free_list 如下,通过引用将指针传递给头节点。

void free_list( struct Node **list ) 
{
    while( *list ) 
    {
        struct Node *current = *list;
        *list = ( *list )->next; 
        free( current ); 
    }
}

由于这些语句,函数 add_back 在为空列表调用时调用未定义的行为

temp = *list; 

while(temp->next != NULL) {

因为最初 *list 等于 NULL.

该函数不应发出任何消息。函数的调用者将决定是否发出消息(如果有)。该函数应通过返回等于 01.

的整数值来报告新节点是否已成功附加

函数可以这样定义。

int add_back( struct Node **list, int value ) 
{
    struct Node *node = malloc( sizeof( struct Node ) );
    int success = node != NULL; 

    if ( success ) 
    {
        node->number = value; 
        node->next = NULL; 

        while( *list != NULL ) 
        {
            list = &( *list )->next; 
        }

        *list = node; 
    }

    return success;
}