我尝试使用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);
}
}
答案 0 :(得分:1)
从评论(以及一些未说明的事情)中纠正所有内容,你得到了这个来源:
#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;
}