gpt4 book ai didi

c - 清除堆栈后打印链表时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:23:09 25 4
gpt4 key购买 nike

更具体地说,这段代码应该是 Unix 函数 dc 的较小克隆。链接列表似乎工作正常。如果我尝试使用 c 来清除内存,添加更多数字,然后使用 f 再次打印,我会遇到段错误。它似乎在打印链表中应该是空节点的内容。

Interaction:
$ ./test
1 2 3
f
3
2
1
c
4 5
f
5
4
0
Segmentation Fault

这是代码本身:

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

struct Node{
int val;
struct Node *next;
};

void cons_node(struct Node **head, int num)
{
struct Node *newNode = malloc(sizeof(struct Node));
newNode->val = num;
newNode->next = NULL;
if (*head == NULL){
*head = newNode;
}
else {
newNode->next = *head;
*head = newNode;
}
}

我假设问题出在显示功能上:

void display_list(struct Node *head)
{
struct Node *current = head;
while(current != NULL)
{
printf("%d\n", current->val);
current = current->next;}

}

void print_top(struct Node *head)
{
printf("%d\n", head->val);
}

或这里的 clear func:

void clear_stack(struct Node *head)
{
struct Node *current;
while ((current = head)!= NULL) {
head = head->next;
free(current);
}
}

void vorpal_func(struct Node *head)
{
struct Node *current;
current = head;
free(current);
}
int main(){

int input;
int first = 1;
char quit = 'n';
char inputchar = ' ';

struct Node *head = NULL;

while (quit == 'n'){

if (scanf("%d", &input) == 1){
cons_node(&head, input);
first = 0;
}

else{
inputchar = getchar();

if(first == 1)
printf("List is empty\n");

else{
switch (inputchar){
case 'q':
quit = 'y';
break;
case 'E':
quit = 'y';
break;
case 'f':
display_list(head);
break;
case 'p':
print_top(head);
break;
case 'c':
clear_stack(head);
first = 1;
break;
case 't':
vorpal_func(head);
break;
}
}
}
}

return 0;
}

几个小时以来,我一直在尝试找出问题所在。有什么建议吗?

最佳答案

您在调用 clear_stack 后并没有清醒头脑,因此当您添加下一个节点时,下一个指针将设置为指向已释放内存的内容。或者,如果您愿意,可以将指向 head 的指针传递给 clear_stack。

void clear_stack(struct Node **head)
{
while (*head != NULL)
{
Node *current = *head;
*head = current->next;
free(current);
}
}

顺便说一下,cons_node 可以这样写

void cons_node(struct Node **head, int num)
{
struct Node *newNode = malloc(sizeof(struct Node));
newNode->val = num;
newNode->next = *head;
*head = newNode;
}

关于c - 清除堆栈后打印链表时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32476844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com