【发布时间】:2020-12-08 05:02:43
【问题描述】:
我目前正在更新我的数据结构知识。今天我决定看看链接列表。我已经完成了单链表和双链表的基本概念。但是,我在 C 中实现循环单链表时遇到了一个小问题。
在创建具有 3 个节点的循环单链表并打印其层次结构后,我想释放节点的内存。但是,每当我尝试运行代码时,都会引发异常。据我了解,问题与free(one); 行有关。正如您在我的代码中看到的那样,我什至尝试预先断开节点之间的链接。这个问题背后的原因是什么,是因为我以错误的方式释放循环链表中的内存吗?如果不是,应该通过什么方法来解决这个问题?
#include <stdio.h>
#include <stdlib.h>
typedef struct NodeSL nodeSL;
struct NodeSL{
int data;
nodeSL *next;
};
void circularLinkedList();
int main(){
/* Circular Link List Example */
circularLinkedList();
return 0;
}
void circularLinkedList(){
/* Initializing the nodes. */
nodeSL *head,*one,*two,*three;
/* Allocating the memory. */
one=(nodeSL*)malloc(sizeof(nodeSL));
two=(nodeSL*)malloc(sizeof(nodeSL));
three=(nodeSL*)malloc(sizeof(nodeSL));
/* Assigning data values. */
one->data=1;
two->data=2;
three->data=3;
/* Connecting the nodes. */
one->next=two;
two->next=three;
three->next=one;
/* Saving the address of the first node in head. */
head=one;
nodeSL *p;
int flag=1;
p=(nodeSL*)malloc(sizeof(nodeSL));
p=head;
printf("THIS IS AN EXAMPLE OF A CIRCULAR LINKED LIST!\n");
printf("Head has the address %u\n",head);
while (flag) {
printf("Data: %d",p->data);
printf("\tAdress: %u",p);
printf("\tPoints Forward to the Address: %u\n",p->next);
p=p->next;
if(p==one)
{
flag=0;
}
}
printf("\n\n");
/* Deallocating the memory. */
three->next=NULL;
two->next=NULL;
one->next=NULL;
head=NULL;
free(p);
free(two);
free(three);
free(one);
}
【问题讨论】:
-
我建议运行 valgrind 来跟踪内存分配问题
-
注明。我目前正在使用 Visual Studio Code 进行编码。我发现它有自己的内存跟踪器功能。无论如何,我会确保将 valgrind 安装到我的 Ubuntu 上。感谢您的建议。
标签: c linked-list dynamic-memory-allocation free circular-list