VM: define initial GC threshold and check malloc for NULL

This commit is contained in:
Andrew Scott 2024-08-20 13:18:35 -04:00
parent 302a0c986b
commit 8568ebe52b
Signed by: a
GPG key ID: 7CD5A5977E4931C1
2 changed files with 22 additions and 5 deletions

26
vm.c
View file

@ -1,14 +1,14 @@
#include <stdio.h>
#include <stdlib.h>
#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);

1
vm.h
View file

@ -2,6 +2,7 @@
#define VM_H
#define STACK_MAX 1024
#define GC_THRESHOLD 256
// Primitive types for garbage collection
enum garbageData {