我正在尝试将一个节点添加到链表的末尾,但是我收到了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;
}
}将节点添加到End函数:
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()函数导致了内存泄漏。
无论如何,任何帮助确定是什么导致堆栈转储的感谢。干杯,托比
发布于 2020-05-13 01:34:47
希望在删除列表中的所有节点之后,指向头节点的指针等于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;
}https://stackoverflow.com/questions/61757402
复制相似问题