aboutsummaryrefslogtreecommitdiffstats
path: root/clox/src/memory.c
diff options
context:
space:
mode:
authorGravatar Tom Willemse2022-08-12 18:22:49 -0700
committerGravatar Tom Willemse2022-08-12 18:22:49 -0700
commit38e4c37f0f991122530a708148a6ec0e2a5a3eff (patch)
tree9d09aa126beda648b6a4f439701fb3290f49c2ef /clox/src/memory.c
parent89ffc2e60a7e7473504721874596e7bebcce896a (diff)
downloadcrafting-interpreters-38e4c37f0f991122530a708148a6ec0e2a5a3eff.tar.gz
crafting-interpreters-38e4c37f0f991122530a708148a6ec0e2a5a3eff.zip
Chapter 26.6
Diffstat (limited to 'clox/src/memory.c')
-rw-r--r--clox/src/memory.c14
1 files changed, 13 insertions, 1 deletions
diff --git a/clox/src/memory.c b/clox/src/memory.c
index c639b65..d1e0c5a 100644
--- a/clox/src/memory.c
+++ b/clox/src/memory.c
@@ -9,13 +9,20 @@
#include <stdio.h>
#endif
+#define GC_HEAP_GROW_FACTOR 2
+
void *reallocate(void *pointer, size_t oldSize, size_t newSize) {
+ vm.bytesAllocated += newSize - oldSize;
if (newSize > oldSize) {
#ifdef DEBUG_STRESS_GC
collectGarbage();
#endif
}
+ if (vm.bytesAllocated > vm.nextGC) {
+ collectGarbage();
+ }
+
if (newSize == 0) {
free(pointer);
return NULL;
@@ -175,6 +182,7 @@ static void sweep() {
void collectGarbage() {
#ifdef DEBUG_LOG_GC
printf("-- gc begin\n");
+ size_t before = vm.bytesAllocated;
#endif
markRoots();
@@ -182,8 +190,12 @@ void collectGarbage() {
tableRemoveWhite(&vm.strings);
sweep();
+ vm.nextGC = vm.bytesAllocated * GC_HEAP_GROW_FACTOR;
+
#ifdef DEBUG_LOG_GC
- printf("-- gd end\n");
+ printf("-- gc end\n");
+ printf(" collected %zu bytes (from %zu to %zu) next at %zu\n",
+ before - vm.bytesAllocated, before, vm.bytesAllocated, vm.nextGC);
#endif
}