【发布时间】:2021-03-27 02:14:09
【问题描述】:
我已经编写了这个 C 代码。一开始,我使用文件处理来读取文本文件并将每一行作为字符串插入到链表中。我需要在一个单独的 void 函数中释放程序中所有的内存分配情况。我怎么做?我只包含了相关的代码部分,因为它是一个相当长的程序。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdbool.h>
#include <ctype.h>
/*Node of linked list*/
typedef struct node {
char *data;
struct node *next;
} node;
node *start = NULL;
node *current;
typedef enum {
not_tested, found, missed
} state;
/*Appending nodes to linked list*/
void add(char *line) {
node *temp = (node *)malloc(sizeof(node));
temp->data = strdup(line);
temp->next = NULL;
current = start;
if (start == NULL) {
start = temp;
}
else {
while (current->next != NULL) {
current = current->next;
}
current->next = temp;
}
}
/*read text file*/
void readfile(char *filename) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
exit(1);
}
char buffer[512];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
add(buffer);
}
fclose(file);
}
【问题讨论】:
-
while(start) { node *p = start; start = start->next; free(p->data); free(p); }- 假设您实际上曾经使用过这些功能,我们甚至不知道,因为您似乎没有main。 -
正如我所说,我省略了其余的代码,因为实际的程序有两百多行,而这些函数实际上只用于一个目的,即构建链表。之后,它们保持不变。
标签: c linked-list malloc strdup