| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- #include "memory.h"
- #include "vm.h"
- #include <stdlib.h>
- // oldSize newSize Operation
- // 0 Non‑zero Allocate new block.
- // Non‑zero 0 Free allocation.
- // Non‑zero Smaller than oldSize Shrink existing allocation.
- // Non‑zero Larger than oldSize Grow existing allocation.
- void *reallocate(void *pointer, size_t oldSize, size_t newSize) {
- if (newSize == 0) {
- free(pointer);
- return NULL;
- }
- /*
- The realloc() function tries to change the size of the allocation pointed
- to by ptr to size, and returns ptr. If there is not enough room to
- enlarge the memory allocation pointed to by ptr, realloc() creates a new
- allocation, copies as much of the old data pointed to by ptr as will fit
- to the new allocation, frees the old allocation, and returns a pointer to
- the allocated memory. If ptr is NULL, realloc() is identical to a call
- to malloc() for size bytes. If size is zero and ptr is not NULL, a new,
- minimum sized object is allocated and the original object is freed. When
- extending a region allocated with calloc(3), realloc(3) does not guaran-
- tee that the additional memory is also zero-filled
- */
- void *result = realloc(pointer, newSize);
- if (result == NULL) exit(1);
- return result;
- }
- static void freeObject(Obj *object) {
- switch (object->type) {
- case OBJ_STRING:
- FREE_ARRAY(char, ((ObjString *) object)->chars, ((ObjString *) object)->length + 1);
- FREE(ObjString, object);
- break;
- }
- }
- void freeObjects() {
- Obj *object = vm.objects;
- while (object != NULL) {
- Obj *next = object->next;
- freeObject(object);
- object = next;
- }
- }
|