bufmalloc.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  2. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
  3. *
  4. * Copyright 2018 (c) Fraunhofer IOSB (Author: Julius Pfrommer)
  5. */
  6. #include "bufmalloc.h"
  7. #define MALLOCMEMBUFSIZE 16384
  8. /* Every element has the memory layout [length (size_t) | buf (length * sizeof(char)) ... ].
  9. * The pointer to buf is returned. */
  10. static char membuf[MALLOCMEMBUFSIZE];
  11. static size_t pos;
  12. static void * membufMalloc(size_t size) {
  13. if(pos + size + sizeof(size_t) > MALLOCMEMBUFSIZE)
  14. return NULL;
  15. char *begin = &membuf[pos];
  16. *((size_t*)begin) = size;
  17. pos += size + sizeof(size_t);
  18. return &begin[sizeof(size_t)];
  19. }
  20. static void membufFree(void *ptr) {
  21. /* Don't do anyting */
  22. }
  23. static void * membufCalloc(size_t nelem, size_t elsize) {
  24. size_t total = nelem * elsize;
  25. void *mem = membufMalloc(total);
  26. if(!mem)
  27. return NULL;
  28. memset(mem, 0, total);
  29. return mem;
  30. }
  31. static void * (membufRealloc)(void *ptr, size_t size) {
  32. size_t orig_size = ((size_t*)ptr)[-1];
  33. if(size <= orig_size)
  34. return ptr;
  35. void *mem = membufMalloc(size);
  36. if(!mem)
  37. return NULL;
  38. memcpy(mem, ptr, orig_size);
  39. return mem;
  40. }
  41. void resetMembuf(void) {
  42. pos = 0;
  43. }
  44. void useMembufAlloc(void) {
  45. pos = 0;
  46. UA_globalMalloc = membufMalloc;
  47. UA_globalFree = membufFree;
  48. UA_globalCalloc = membufCalloc;
  49. UA_globalRealloc = membufRealloc;
  50. }
  51. void useNormalAlloc(void) {
  52. UA_globalMalloc = malloc;
  53. UA_globalFree = free;
  54. UA_globalCalloc = calloc;
  55. UA_globalRealloc = realloc;
  56. }