padariadoce
padariadoce

Reputation: 13

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. I appreciate any help given. Thank you!

Upvotes: 0

Views: 55

Answers (1)

dbush
dbush

Reputation: 225507

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.

Upvotes: 1

Related Questions