c/c++语言开发共享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 filen"); 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了。

      以上就是c/c++开发分享C中链表的可用内存相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/519755.html

      (0)
      上一篇 2020年12月5日
      下一篇 2020年12月5日

      精彩推荐