I’m fairly new to Pointers and the memory model so excuse me if this is obvious, but I am writing a program to test a function reverse that reverses a list. Anyway I have it in three files, C5.c, C5-driver.c, and C5.h. Here they are in that order:
#include "C5.h"
#include <stdlib.h>
#include <stdio.h>
struct node *cons(int fst, struct node *rst) {
struct node *new = malloc(sizeof(struct node));
if (new == NULL) {
printf("cons: out of memory\n");
abort();
}
(*new).first = fst; /* same as (*new).first = fst */
(*new).rest = rst;
return new;
}
struct node *reverse(struct node *lst) {
struct node *ans = NULL;
while (lst != NULL) {
ans = cons((*lst).first, ans);
lst = (*lst).rest;
}
return ans;
}
void free_list(struct node *lst) {
struct node *p;
while (lst != NULL) {
p = lst->rest;
free(lst);
lst = p;
}
}
void print_list(struct node *lst) {
printf("( ");
while (lst != NULL) {
printf("%d ", (*lst).first);
lst = (*lst).rest;
}
printf(")\n");
}
C5-driver.c
#include <stdlib.h> #include <stdio.h> #include "C5.h" int main() { struct node *lst1 = cons(5, NULL); struct node *lst2 = cons(3, lst1); struct node *lst3 = cons(1, lst2); print_list(lst3); lst3 = reverse(lst3); print_list(lst3); free_list(lst3); }C5.h
struct node {
int first;
struct node *rest;
};struct node *cons(int ,struct node *);
struct node *reverse(struct node *);
void print_list(struct node *);
void free_list(struct node *);
However I’m told by XCode that there are memory leaks.
I’m assuming it’s after cons is used however I’ve tried creating a new
struct node *ans = newand free(new); with return ans; but that doesn’t work. I’ve also tried free_list as you can see above.Thanks~
The reverse function calls cons which allocates memory, then it overwrites the lst3 pointer. The memory leak is that lst3 is overwritten which makes it impossible to recover that memory.
You should probably make a new variable like
struct node *lst3_reverseandlst3_reverse = reverse(lst3). Then you can safely dofree_list(lst3)andfree_list(lst3_reverse)to free the memory.