我的代码有一些问题:我不能使用我写的函数重新创建我的图形。
#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语言的新手,即使在谷歌了几个小时之后也是如此。我很感谢大家给予的帮助。谢谢!
发布于 2020-03-11 04:16:44
一旦释放了内存,就不允许取消引用曾经指向它的指针。这样做会调用undefined behavior,其中包含看起来仍然存在的数据。
如果你真的想检查内存是否被正确处理,可以通过valgrind这样的内存检查器运行你的代码。
https://stackoverflow.com/questions/60625205
复制相似问题