看了谭浩强的《C语言程序设计》上面教的链表,发现申请的内存没有释放,我试着写了一下。
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
struct Stu
{
int data;
struct Stu* next;
};
void test1()
{
//链表尾声明
struct Stu* head=NULL, * p;
int num = 0;
p = (struct Stu*)malloc(sizeof(struct Stu));
if (p == NULL)
{
perror("p malloc");
return;
}
p->next = NULL;
//输入
printf("您希望创建几组数据:");
scanf("%d", &num);
for (size_t i = 0; i < num; i++)
{
printf("请输入数据---数字:");
scanf("%d", &p->data);
head = (struct Stu*)malloc(sizeof(struct Stu));
if (head == NULL)
{
perror("没有更多的堆空间能够开辟");
return;
}
head->next = p;
p = head;
}
//最初一个为空,直接跳过
p = p->next;
//输出
for (size_t i = 0; i < num; i++)
{
printf("%d ", p->data);
p = p->next;
}
//释放堆区内存
struct Stu* ret = head;
for (size_t i = 0; i < num; i++)
{
if (ret == NULL)
{
perror("ret == NULL");
return;
}
head = head->next;
free(ret);
ret = head;
}
free(ret);
ret = NULL;
head = NULL;
}
int main()
{
test1();
return 0;
}
虽然浪费了一个空间,但是链表尾的指针不是一个野指针。这样释放应该也都释放干净了。