summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorubq323 <ubq323@ubq323.website>2023-08-04 23:05:22 +0100
committerubq323 <ubq323@ubq323.website>2023-08-04 23:05:22 +0100
commit93fe66fb8ef5c731b46a30a804f74b4bf3b133d7 (patch)
treef3c1121f992ac6d651af22e03ad55a44a8c84e2c
parentf67a3fd05c1b2fe8c749fc2f58287b1b14b011d8 (diff)
give M extra param for tracking alloc size; macros for allocation
-rw-r--r--mem.c12
-rw-r--r--mem.h13
-rw-r--r--val.c5
-rw-r--r--vm.c6
4 files changed, 27 insertions, 9 deletions
diff --git a/mem.c b/mem.c
index 6e0bc1b..d464f7d 100644
--- a/mem.c
+++ b/mem.c
@@ -3,12 +3,12 @@
#include <stdio.h>
#include <stdlib.h>
-void *M(void *p, size_t sz) {
- if (sz == 0) {
+void *M(void *p, size_t old, size_t new) {
+ if (new == 0) {
free(p);
return NULL;
} else {
- void *x = realloc(p, sz);
+ void *x = realloc(p, new);
if (x == NULL) {
printf("out of memory! aaaaaaa!!!!!\n");
exit(42);
@@ -16,3 +16,9 @@ void *M(void *p, size_t sz) {
return x;
}
}
+
+Obj *alloc_obj(size_t sz, ObjTy oty) {
+ Obj *o = M(NULL, 0, sz);
+ o->oty = oty;
+ return o;
+}
diff --git a/mem.h b/mem.h
index 8f66fed..0607b14 100644
--- a/mem.h
+++ b/mem.h
@@ -2,7 +2,18 @@
#define _mem_h
#include <stddef.h>
+#include "val.h"
+
+void *M(void *p, size_t old, size_t new);
+
+#define NEW(t) (t*)M(NULL, 0, sizeof(t))
+#define NEW_ARR(t,n) (t*)M(NULL, 0, (n)*sizeof(t))
+#define RENEW_ARR(p,t,old,new) (t*)M((p), (old)*sizeof(t), (new)*sizeof(t))
+#define NEW_OBJ(t, oty) (t*)alloc_obj(sizeof(t), oty)
+
+#define FREE(p,t) M(p, sizeof(t), 0)
+
+Obj *alloc_obj(size_t sz, ObjTy oty);
-void *M(void *p, size_t sz);
#endif
diff --git a/val.c b/val.c
index c1b83c3..355aac6 100644
--- a/val.c
+++ b/val.c
@@ -5,11 +5,10 @@
ObjString *objstring_new(char *src, size_t len) {
- char *d = M(NULL, (1 + len) * sizeof (char));
+ char *d = NEW_ARR(char, 1+len);
memcpy(d, src, len);
d[len] = '\0';
- ObjString *o = M(NULL, sizeof(ObjString));
- o->obj.oty = OTY_STRING;
+ ObjString *o = NEW_OBJ(ObjString, OTY_STRING);
o->len = len;
o->b = d;
return o;
diff --git a/vm.c b/vm.c
index a9610d2..4933614 100644
--- a/vm.c
+++ b/vm.c
@@ -16,10 +16,12 @@ Chunk chunk_new() {
.clen = 0, .ccap = 0, .c = NULL,
};
}
+
+
size_t chunk_wbc(Chunk *ch, uint8_t byte) {
if (ch->blen == ch->bcap) {
size_t newsz = (ch->bcap == 0 ? 8 : ch->bcap * 2);
- ch->b = M(ch->b, newsz * sizeof(uint8_t));
+ ch->b = RENEW_ARR(ch->b, uint8_t, ch->bcap, newsz);
ch->bcap = newsz;
}
size_t ix = ch->blen;
@@ -30,7 +32,7 @@ size_t chunk_wbc(Chunk *ch, uint8_t byte) {
size_t chunk_wconst(Chunk *ch, Val v) {
if (ch->clen == ch->ccap) {
size_t newsz = (ch->ccap == 0 ? 8 : ch->ccap *2);
- ch->c = M(ch->c, newsz * sizeof(Val));
+ ch->c = RENEW_ARR(ch->c, Val, ch->ccap, newsz);
ch->ccap = newsz;
}
size_t ix = ch->clen;