memory.c 1.3 KB

123456789101112131415161718192021222324252627282930
  1. #include "memory.h"
  2. #include <stdlib.h>
  3. // oldSize newSize Operation
  4. // 0 Non‑zero Allocate new block.
  5. // Non‑zero 0 Free allocation.
  6. // Non‑zero Smaller than oldSize Shrink existing allocation.
  7. // Non‑zero Larger than oldSize Grow existing allocation.
  8. void *reallocate(void *pointer, size_t oldSize, size_t newSize) {
  9. if (newSize == 0) {
  10. free(pointer);
  11. return NULL;
  12. }
  13. /*
  14. The realloc() function tries to change the size of the allocation pointed
  15. to by ptr to size, and returns ptr. If there is not enough room to
  16. enlarge the memory allocation pointed to by ptr, realloc() creates a new
  17. allocation, copies as much of the old data pointed to by ptr as will fit
  18. to the new allocation, frees the old allocation, and returns a pointer to
  19. the allocated memory. If ptr is NULL, realloc() is identical to a call
  20. to malloc() for size bytes. If size is zero and ptr is not NULL, a new,
  21. minimum sized object is allocated and the original object is freed. When
  22. extending a region allocated with calloc(3), realloc(3) does not guaran-
  23. tee that the additional memory is also zero-filled
  24. */
  25. void *result = realloc(pointer, newSize);
  26. if (result == NULL) exit(1);
  27. return result;
  28. }