我有以下定义链表节点的结构代码
struct list {
struct student s;
struct list *next;
};
我的学生结构定义如下
struct student{
unsigned short year;
unsigned short grade;
unsigned char *details;
};
假设我的程序创建了一个学生链表,我想编写一个函数来释放我进行的每个 malloc 调用。
在我的程序中,每次初始化 *details 时,以及每次为列表创建节点时,我都会调用 malloc。
如果这有帮助,这是我创建节点的函数:
struct list *create_node(struct student *p) {
struct list *node = malloc(sizeof(struct list));
node->p = *p;
node->next = NULL;
return node;
}
我想写一个函数来释放所有用 malloc 来保存列表的内存。
这是我的尝试
void free_list(struct list *node){
// free this first node
free(node->p.details);
while (node->next != NULL){
// become the next node and free
node = node->next;
free(node->p.details);
}
最佳答案
你的免费功能可以是这样的
void free_list(struct list *node){
struct list *temp = NULL;
// free this first node
//free(node->p.details);
while (node != NULL){
temp = node;
// become the next node and free
node = node->next;
free(temp->p.details);
temp->p.details = NULL;
free(temp);
}
关于c - 编写一个函数来释放从链表创建的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21668369/