From 8568ebe52b3fa43e935825cf88e43d104af80aa6 Mon Sep 17 00:00:00 2001 From: Andrew Scott Date: Tue, 20 Aug 2024 13:18:35 -0400 Subject: [PATCH] VM: define initial GC threshold and check malloc for NULL --- vm.c | 26 +++++++++++++++++++++----- vm.h | 1 + 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/vm.c b/vm.c index 68d37b7..d90dad7 100644 --- a/vm.c +++ b/vm.c @@ -1,14 +1,14 @@ #include #include -#include "vm.h" #include "gc.h" +#include "vm.h" struct virtualMachine *initVM() { struct virtualMachine *vm = malloc(sizeof(struct virtualMachine)); vm->stackSize = 0; vm->refCount = 0; - vm->refMax = STACK_MAX / 2; + vm->refMax = GC_THRESHOLD; vm->head = NULL; return vm; } @@ -23,8 +23,7 @@ void push(struct virtualMachine *vm, struct garbageObject *value) { struct garbageObject *pop(struct virtualMachine *vm) { if (vm->stackSize < 0) { - fprintf(stderr, - "ERROR: pop(): Stack size cannot be negative!"); + fprintf(stderr, "ERROR: pop(): Stack size cannot be negative!"); return NULL; } @@ -33,9 +32,17 @@ struct garbageObject *pop(struct virtualMachine *vm) { struct garbageObject *initGarbage(struct virtualMachine *vm, enum garbageData type) { - if (vm->refCount == vm->refMax) collect(vm); + + if (vm->refCount >= vm->refMax) { + collect(vm); + } struct garbageObject *obj = malloc(sizeof(struct garbageObject)); + if (obj == NULL) { + fprintf(stderr, "initGarbage(): Allocation failure!"); + return obj; + } + obj->type = type; obj->mark = 0; obj->next = vm->head; @@ -46,12 +53,21 @@ struct garbageObject *initGarbage(struct virtualMachine *vm, void pushInt(struct virtualMachine *vm, int value) { struct garbageObject *obj = initGarbage(vm, GARBAGE_INT); + if (obj == NULL) { + fprintf(stderr, "pushInt(): Unable to create GARBAGE_INT - out of memory?"); + } + obj->value = value; push(vm, obj); } struct garbageObject *pushPair(struct virtualMachine *vm) { struct garbageObject *obj = initGarbage(vm, GARBAGE_PAIR); + if (obj == NULL) { + fprintf(stderr, + "pushPair(): Unable to create GARBAGE_PAIR - out of memory?"); + } + obj->tail = pop(vm); obj->head = pop(vm); diff --git a/vm.h b/vm.h index 90803e4..8e7f0bc 100644 --- a/vm.h +++ b/vm.h @@ -2,6 +2,7 @@ #define VM_H #define STACK_MAX 1024 +#define GC_THRESHOLD 256 // Primitive types for garbage collection enum garbageData {