From 50d6dd8b50958271bf1ff13f99dc21d4cd8431f7 Mon Sep 17 00:00:00 2001 From: Peter Mikkelsen Date: Thu, 13 Jan 2022 19:45:22 +0000 Subject: Implement basic reference counting for arrays, which so they get freed when not in use anymore. --- memory.c | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 memory.c (limited to 'memory.c') diff --git a/memory.c b/memory.c new file mode 100644 index 0000000..adc0466 --- /dev/null +++ b/memory.c @@ -0,0 +1,53 @@ +#include +#include +#include + +#include "apl9.h" + +int alloccounts = 0; + +void +freearray(Array *a) +{ + a->refs--; + if(a->refs == 0){ + /* print("Freeing array: %S (%p)\n", pparray(a), a); */ + if(a->type == AtypeArray) + for(int i = 0; i < a->size; i++) + freearray(a->arraydata[i]); + free(a->shape); + free(a); + alloccounts--; + }else if(a->refs > 0){ + /* print("Not freeing (refs=%d): %S (%p)\n", a->refs, pparray(a), a); */ + }else{ + print("NEGATIVE REF COUNT! %p\n", a); + exits(nil); + } +} + +Array * +allocarray(arrayDataType t, int rank, int size) +{ + Array *a = malloc(sizeof(Array)); + a->rank = rank; + a->type = t; + a->size = size; + a->stranded = 0; + a->shape = malloc(sizeof(int) * rank); + a->rawdata = malloc(datasizes[t] * size); + a->type = t; + a->refs = 1; + alloccounts++; + return a; +} + +void +incref(Array *a) +{ + /* print("INCREF %d->%d %S\n", a->refs, a->refs+1, pparray(a)); */ + a->refs++; + if(a->type == AtypeArray) + for(int i = 0; i < a->size; i++) + incref(a->arraydata[i]); +} \ No newline at end of file -- cgit v1.2.3