gpt4 book ai didi

C:尝试使用 malloc 创建列表时出现段错误

转载 作者:行者123 更新时间:2023-11-30 15:27:17 25 4
gpt4 key购买 nike

我正在尝试使用 malloc 创建一个列表,程序获取用户输入的整数,并在用户输入 0 时退出。但是我收到了段错误(核心转储)错误,但我还没有无法发现问题。我尝试过的事情包括添加“liberar”方法来释放内存,但它也不起作用。谢谢!

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

struct list1 {
int val;
struct list1 * sig;
};

typedef struct list1 i;

void main() {
i * aux, * cabeza;
int entrada;

cabeza = NULL;

while(1) {
aux = (i*)malloc(sizeof(i));
scanf("%d\n",entrada);
if(entrada==0){
exit(0);
}
aux->val = entrada;
aux->sig = cabeza;
cabeza = aux;
liberar(cabeza);
}

aux = cabeza;

while(aux) {
printf("%d\n", aux->val);
aux = aux->sig ;
}
}

int liberar(struct list1* cabez)
{
struct list1 *temp;
while (cabez != NULL)
{
temp = cabez;
cabez = cabez->sig;
free(temp);
}

}

最佳答案

纠正评论中的所有内容(以及一些未说的内容),您将得到以下来源:

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

typedef struct List {
int val;
struct List * next;
} List;

void list_free(List * list)
{
while (list != NULL)
{
List *temp = list;
list = list->next;
free(temp);
}
}

int main() {
List * aux, * result;
int input;

result = NULL;

while(1) {
scanf("%d",&input);
if(input == 0){
break;
}
aux = (List *)malloc(sizeof(List));
assert(aux != NULL);
aux->val = input;
aux->next = result;
result = aux;
}

aux = result;

printf("Result =\n");

while(aux) {
printf("%d\n", aux->val);
aux = aux->next;
}

list_free(result);

return 0;
}

关于C:尝试使用 malloc 创建列表时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27079788/

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