我正在努力尝试将节点添加到链表的末尾,但我收到了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
.
该函数不得发出任何消息。函数的调用方将决定是否发出消息(如果有(。该函数应通过返回等于0
或1
的整数值来报告新节点是否已成功追加。
可以通过以下方式定义该函数。
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;
}