Skip to content

Commit

Permalink
VM: fix some memory leaks
Browse files Browse the repository at this point in the history
  • Loading branch information
mrunix00 committed Sep 13, 2024
1 parent 1ecef62 commit 4bbf4cd
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
2 changes: 1 addition & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.28)
project(HAL64 C)

set(CMAKE_C_STANDARD 90)
add_compile_options(-Ofast)
add_compile_options(-O0)
set(LEXER_DIR "${CMAKE_CURRENT_BINARY_DIR}")
set(LEXER_OUT "${LEXER_DIR}/lexer.c")

Expand Down
16 changes: 15 additions & 1 deletion src/hal64.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,26 @@
#include "hal64.h"
#include "utils/memory.h"

static void
free_instructions(Instruction *instructions, size_t count)
{
size_t i;
for (i = 0; i < count; i++) {
if (instructions[i].op == OP_PUSH_LITERAL_STRING)
free(instructions[i].data.string.ptr);
}
}

void
free_program(Program program)
{
size_t i;
for (i = 0; i < program.functions_count; i++)
for (i = 0; i < program.functions_count; i++) {
free_instructions(
program.functions[i].instructions,
program.functions[i].instructions_count);
free(program.functions[i].instructions);
}
free(program.functions);
}

Expand Down
9 changes: 9 additions & 0 deletions src/vm.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ init_vm(void)
vm.operands_stack.capacity = 1024;
vm.pointers_stack.capacity = 1024;
vm.objects.capacity = 1024;
vm.allocated_heap_size = 0;
vm.call_stack.data = safe_malloc(vm.call_stack.capacity * sizeof(uint64_t));
vm.operands_stack.data = safe_malloc(vm.operands_stack.capacity * sizeof(uint64_t));
vm.pointers_stack.data = safe_malloc(vm.pointers_stack.capacity * sizeof(HeapObject *));
Expand All @@ -26,8 +27,15 @@ init_vm(void)
void
free_vm(VM vm)
{
size_t i;
free(vm.call_stack.data);
free(vm.operands_stack.data);
free(vm.pointers_stack.data);
for (i = 0; i < vm.objects.size; i++) {
free(vm.objects.data[i]->data);
free(vm.objects.data[i]);
}
free(vm.objects.data);
}

static void
Expand All @@ -45,6 +53,7 @@ gc_sweep(VM *vm)
size_t i;
for (i = 0; i < vm->objects.size; i++) {
if (!vm->objects.data[i]->marked) {
vm->allocated_heap_size -= vm->objects.data[i]->size;
free(vm->objects.data[i]->data);
free(vm->objects.data[i]);
vm->objects.data[i] = vm->objects.data[vm->objects.size - 1];
Expand Down

0 comments on commit 4bbf4cd

Please sign in to comment.