mem.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #ifndef ERUTA_MEM_H
  2. #define ERUTA_MEM_H
  3. #include <stdlib.h>
  4. /* Wrapper for calloc/malloc */
  5. void * mem_calloc(size_t amount, size_t size);
  6. /* Wrapper for calloc/malloc */
  7. void * mem_alloc(size_t size);
  8. /* Wrapper for free */
  9. void * mem_free(void * ptr);
  10. /* Wrapper for realloc */
  11. void * mem_realloc(void *ptr, size_t newsize);
  12. /* Resizes memory, taking care not to lose ptr* if the reallocation
  13. fails. */
  14. void * mem_resize(void ** ptr, size_t newsize);
  15. /* Wrapper for memmove, for consistency */
  16. void * mem_move(void * dest, void * src, size_t size);
  17. /* A function pointer that can act as a destructor.
  18. Should return NULL on sucessful freeing, and non-null
  19. if freeing failed. */
  20. typedef void * (MemDestructor)(void * ptr);
  21. /* Counted reference. Just an idea... */
  22. struct Refc {
  23. void * ptr;
  24. int refc;
  25. MemDestructor * destroy;
  26. };
  27. /* Handy macros. */
  28. /*
  29. #define STRUCT_NALLOC(STRUCT, AMOUNT) \
  30. ((STRUCT *) mem_calloc(sizeof(STRUCT), (AMOUNT)))
  31. */
  32. #define MEM_ALLOCATE(STRUCTNAME) mem_alloc(sizeof(STRUCTNAME))
  33. #define STRUCT_NALLOC(STRUCT, AMOUNT) \
  34. (mem_calloc(sizeof(STRUCT), (AMOUNT)))
  35. #define STRUCT_ALLOC(STRUCT) \
  36. ((STRUCT *)MEM_ALLOCATE(STRUCT))
  37. #define STRUCT_FREE(VAR) \
  38. mem_free(VAR)
  39. #endif