因此,我无法释放已分配给我的链接列表数组的内存。释放一系列链接列表
这里是我的typedef struct
:
typedef struct Node {
int id;
int degree;
int distance;
int status;
struct Node *next;
} Node;
这里就是我创建阵列
Node *graph = malloc(sizeof(Node) * N);
if (graph == NULL) {
printf("Fatal Error: Out of memory!\n");
exit(1);
}
for (int i=0; i < N; i++) {
n = create_node(i);
graph[i] = *(n);
}
Node *graph2 = malloc(sizeof(Node) * N);
if (graph2 == NULL) {
printf("Fatal Error: Out of memory!\n");
exit(1);
}
for (int i=0; i < N; i++) {
n = create_node(i);
graph2[i] = *(n);
}
这里是create_node
:
Node* create_node(int id) {
// Allocate memory for the structure
Node *n = malloc(sizeof (Node));
if (n == NULL) {
printf("Fatal Error: Out of memory!\n");
exit(1);
}
n->id = id; // set the value that identifies the node
n->distance = INT_MAX; //we don't know teh source yet, so distance is infinity
n->next = NULL;
n->status = 0;
return n; }
这里是我尝试免费的代码阵列
for (int i=0; i < N; i++) {
free_node(&graph[i]);//<---here
graph = NULL;
free_node(&graph2[i]);
graph2 = NULL;
}
这是我free_node
功能:
int free_node(Node *n) {
Node *tmp = malloc(sizeof(Node));
while (n != NULL) {//<---here
tmp = n;
n = n.next;
free(tmp);
tmp = NULL;
}
return 0;
}
我得到的代码标记以上的线路分段错误的“< ---在这里”为在该行结尾的注释。它从我的free_node函数开始,它从释放graph[i]
被调用。
欢迎来到Stack Overflow。请尽快阅读[关于]页面。你已经展示了我们需要的大部分代码。你不会显示'create_node()'函数,这会显示你是否合理地初始化结构的'next'成员。这可能是解决问题的关键。 'free_node()'中的内存分配也非常出乎意料。事实上,它通常是一个泄漏(假设'n'通常不为空)。在循环内使用'Node * tmp = n;'并删除分配。这可能与事故不相关,但这是一个真正的问题,也需要修复。 – 2014-11-01 20:41:13