[英]Can't free allocated memory
Im having some issues with my code: I cannot recreate my graph using the function I wrote.我的代码有一些问题:我无法使用我编写的函数重新创建图形。
#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;
}
This function was supposed to free all the memory allocated to my structure.这个函数应该释放分配给我的结构的所有内存。 However It doesn't work because I can print any addresses of my structure after running this function.但是它不起作用,因为我可以在运行此函数后打印我的结构的任何地址。 I can't diagnose the source of this issue as Im still new to C even after googling It for hours.我无法诊断这个问题的根源,因为即使在谷歌搜索了几个小时之后,我还是 C 的新手。 I appreciate any help given.我感谢您提供的任何帮助。 Thank you!谢谢!
Once you free memory, you are not allowed to dereference the pointers that once pointed to it.一旦释放内存,就不允许取消引用曾经指向它的指针。 Doing so invokes undefined behavior , which includes the data appearing to still be there.这样做会调用未定义的行为,其中包括似乎仍然存在的数据。
If you really want to check that memory was handled properly, run your code through a memory checker like valgrind.如果您真的想检查内存是否被正确处理,请通过内存检查器(如 valgrind)运行您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.