C中链表的可用内存

我一直试图释放加载到链表中的文件的已分配内存,我已设法释放节点,但我无法弄清楚如何释放文件的值副本的已分配内存。

我尝试过这样的事情:

void FreeString(struct node * newNode) { for (int i = 0; i string); } } 

但是编译器会因为分段错误而崩溃,而valgrind仍会指出内存泄漏。

如果有人能告诉我我做错了什么,并指出正确的方向,我们将不胜感激。

完整代码:

结构:

 typedef struct node { char *string; struct node *next; }node; 

//这里的主要function……

 void Push(struct node **RefHead, char *word) { struct node *newNode = NULL; newNode = (struct node *)malloc(sizeof(node)); newNode->string = (char*)malloc(strlen(word) + 1); // can't free this part here strcpy(newNode->string, word); newNode->next = *RefHead; *RefHead = newNode; } 

将文件加载到内存中:

 void FileToNode() { struct node *head = NULL, *current = NULL; infile = fopen("file.txt", "r"); if (infile == NULL) { printf("Could not open file\n"); exit(1); } while (fgets(word, sizeof(word), infile)) { Push(&head, word); } fclose(infile); current = head; while(current) { printf("%s", current->string); current = current->next; } freeAll(head); } 

自由function:

 void freeAll(struct node *head) { struct node *current = NULL; while ((current = head) != NULL) { head = head->next; free(current); } } 

我错过了什么吗? 出了什么问题:

 void freeAll(struct node *head) { struct node *current = NULL; while ((current = head) != NULL) { head = head->next; free(current->string); free(current); } } 

这不是问题,但你应该更换:

 newNode->string = (char*)malloc(strlen(word) + 1); // can't free this part here strcpy(newNode->string, word); 

有:

 newNode->string = strdup (word); 

问题是这样的:

 void FreeString(struct node * newNode) { for (int i = 0; i < 5; i++) { free(newNode->string); } } 

一旦你调用freenewNode->string就不再指向一个已分配的对象(因为你刚刚释放它)。 所以你不能再把它传给free了。