c语言 - 无法释放分配的内存



我的代码有一些问题:我无法使用我编写的函数重新创建我的图。

#include <stdio.h>
#include <stdlib.h>
#define maxNodes 4
typedef struct edge {
int target;
struct edge* next;
} edge;
typedef struct node {
edge* start;
} node;
int isInvalidInput(int input) {
if(input > 3 && input < 0) {
puts("Invalid input");
return 1;
}
return 0;
}
int recreateGraph(node* graph) {
edge* roam;
for(int index = 0; index < maxNodes; index++) {
roam = graph[index].start;
while(roam) {
edge* aux = roam;
roam = roam->next;
free(aux);
aux = NULL;
}
}
return 0;
}
int deleteEdge(node* graph, int node, int target) {
if(!graph[node].start) {
return 1;
}
edge* roam = graph[node].start;
if(roam->target == target) {
edge* aux = roam;
graph[node].start = roam->next;
free(aux);
return 0;
}
while(roam->next) {
if(roam->target == target) {
edge* aux = roam;
roam = roam->next;
free(aux);
return 0;
}
roam = roam->next;
}
return 1;
}
int insertEdge(node* graph, int from, int to) {
if(isInvalidInput(from) == 1 && isInvalidInput(to) == 1) return 1;
if(!graph[from].start) {
graph[from].start = (edge*) malloc(sizeof(edge));
graph[from].start->target = to;
return 1;
}
edge* roam = graph[from].start;
while(roam->next) {
roam = roam->next;
}
roam->next = (edge*) malloc(sizeof(edge));
roam->next->target = to;
return 0;
}
node* createGraph() {
node* graph = (node*) malloc(sizeof(graph) * maxNodes);
for(int index = 0; index < maxNodes; index++) {
graph[index].start = (edge*) malloc(sizeof(edge));
graph[index].start = NULL;
}
return graph;
}
int main()
{
node* graph = createGraph();
insertEdge(graph, 0, 2);
insertEdge(graph, 0, 1);
insertEdge(graph, 2, 1);
//deleteEdge(graph, 0, 1);
recreateGraph(graph);
printf("%i ", graph[0].start->next);
return 0;
}

这个函数应该释放分配给我的结构的所有内存。然而,它不起作用,因为运行此函数后,我可以打印结构的任何地址。我无法诊断这个问题的来源,因为即使在谷歌上搜索了几个小时,我仍然是C的新手。我感谢你的帮助。非常感谢。

一旦释放内存,就不允许取消引用曾经指向它的指针。这样做会调用未定义的行为,其中包括看起来仍然存在的数据。

如果你真的想检查内存是否被正确处理,可以通过valgrind这样的内存检查器来运行你的代码。

最新更新