【发布时间】:2021-12-03 10:36:49
【问题描述】:
我需要实现一个链表,它将文件名和信息存储为每个节点。 我决定将节点填充为:
struct node
{
struct stat st;
char filename[FILENAME_MAX];
struct node *next;
};
我希望我的程序根据任何给定目录中的文件名创建一个链接列表。 我已经制作了几个函数来做到这一点。
(xmalloc 只是 malloc 的一个包装器,如果 malloc 出于某种原因返回 null,它会退出程序) 将节点添加到现有列表:
struct node *
add_list(struct node **head, struct node n)
{
struct node *new = xmalloc(sizeof(struct node));
memcpy(new, &n, sizeof(struct node));
new->next = NULL;
new->next = *head;
*head = new;
return new;
}
用给定目录中的文件填充列表:
int
fill_list(struct node **head, const char *dirname)
{
DIR *dir;
struct dirent *de;
if ((dir = opendir(dirname)) == NULL)
{
perror("(fill_list) opendir");
free_list(head);
exit(EXIT_FAILURE);
}
while (de = readdir(dir))
{
// Don't add entries for parent dir and current fir
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
continue;
struct node new_node;
new_node.next = NULL;
strncpy((new_node.filename), (de->d_name), FILENAME_MAX);
stat(de->d_name, &(new_node.st));
add_list(head, new_node);
}
}
释放现有列表:
free_list(struct node** head)
{
struct node* current = *head;
struct node* next = NULL;
while (current->next != NULL)
{
next = current->next;
printf("free: %p\n", current);
current = next;
}
*head = NULL;
}
最后,打印列表的内容:
int
print_list(struct node *head)
{
while (head->next)
{
printf("%s: %ld\n", head->filename, head->st.st_size);
head = head->next;
}
}
我的主要功能是
int main(void)
{
struct node *head;
fill_list(&head, ".");
print_list(head);
free_list(&head);
}
由于某种原因,当我运行此代码时,有时会出现分段错误,但并非总是如此。
我的目录包含
a.out list.h llist.c log_synfiles.log syncfiles syncfiles.c test.c
当它正常运行时,会出现内存泄漏。
为什么会这样?
【问题讨论】:
-
为什么使用 xmalloc 而不是 malloc?您没有检查 xmalloc 返回的内容。是空的吗?
-
@AbelTom xmalloc 不能返回 null,它只是 malloc 的一个包装器,如果 malloc 出于某种原因返回 null 则退出程序
标签: c memory-leaks linked-list segmentation-fault