memory.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include "memory.h"
  2. #include "vm.h"
  3. #include <stdlib.h>
  4. // oldSize newSize Operation
  5. // 0 Non‑zero Allocate new block.
  6. // Non‑zero 0 Free allocation.
  7. // Non‑zero Smaller than oldSize Shrink existing allocation.
  8. // Non‑zero Larger than oldSize Grow existing allocation.
  9. void *reallocate(void *pointer, size_t oldSize, size_t newSize) {
  10. if (newSize == 0) {
  11. free(pointer);
  12. return NULL;
  13. }
  14. /*
  15. The realloc() function tries to change the size of the allocation pointed
  16. to by ptr to size, and returns ptr. If there is not enough room to
  17. enlarge the memory allocation pointed to by ptr, realloc() creates a new
  18. allocation, copies as much of the old data pointed to by ptr as will fit
  19. to the new allocation, frees the old allocation, and returns a pointer to
  20. the allocated memory. If ptr is NULL, realloc() is identical to a call
  21. to malloc() for size bytes. If size is zero and ptr is not NULL, a new,
  22. minimum sized object is allocated and the original object is freed. When
  23. extending a region allocated with calloc(3), realloc(3) does not guaran-
  24. tee that the additional memory is also zero-filled
  25. */
  26. void *result = realloc(pointer, newSize);
  27. if (result == NULL) exit(1);
  28. return result;
  29. }
  30. static void freeObject(Obj *object) {
  31. switch (object->type) {
  32. case OBJ_FUNCTION: {
  33. ObjFunction *function = (ObjFunction *) object;
  34. freeChunk(&function->chunk);
  35. FREE(ObjFunction, object);
  36. break;
  37. }
  38. case OBJ_STRING:
  39. FREE_ARRAY(char, ((ObjString *) object)->chars, ((ObjString *) object)->length + 1);
  40. FREE(ObjString, object);
  41. break;
  42. }
  43. }
  44. void freeObjects() {
  45. Obj *object = vm.objects;
  46. while (object != NULL) {
  47. Obj *next = object->next;
  48. freeObject(object);
  49. object = next;
  50. }
  51. }