Allocator_test.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "util/Assert.h"
  16. #include <stdint.h>
  17. #include <stdio.h>
  18. #include "memory/Allocator.h"
  19. #include "memory/Allocator_pvt.h"
  20. #include "memory/MallocAllocator.h"
  21. #ifdef Allocator_USE_CANARIES
  22. #define ALLOCATION_SIZE sizeof(struct Allocator_Allocation_pvt) + sizeof(long)
  23. #else
  24. #define ALLOCATION_SIZE sizeof(struct Allocator_Allocation_pvt)
  25. #endif
  26. #define ALLOCATOR_SIZE sizeof(struct Allocator_pvt)
  27. static int increment(int* num)
  28. {
  29. (*num)++;
  30. return 1;
  31. }
  32. struct TestStruct {
  33. int value;
  34. };
  35. static void allocatorClone()
  36. {
  37. struct Allocator* alloc = MallocAllocator_new(2048);
  38. int calls = 0;
  39. struct TestStruct* ts = Allocator_clone(alloc, (&(struct TestStruct) {
  40. .value = increment(&calls)
  41. }));
  42. Assert_true(calls == 1);
  43. Assert_true(ts->value == 1);
  44. Allocator_free(alloc);
  45. }
  46. static void structureSizes()
  47. {
  48. struct Allocator* alloc = MallocAllocator_new(2048);
  49. size_t bytesUsed;
  50. bytesUsed = Allocator_bytesAllocated(alloc);
  51. Assert_true(bytesUsed == ALLOCATION_SIZE + sizeof(struct Allocator_FirstCtx));
  52. Allocator_malloc(alloc, 25);
  53. bytesUsed += (((25 / sizeof(char*)) + 1) * sizeof(char*)) + ALLOCATION_SIZE;
  54. Assert_true(Allocator_bytesAllocated(alloc) == bytesUsed);
  55. struct Allocator* child = Allocator_child(alloc);
  56. bytesUsed += ALLOCATION_SIZE + ALLOCATOR_SIZE;
  57. Assert_true(Allocator_bytesAllocated(alloc) == bytesUsed);
  58. Allocator_malloc(child, 30);
  59. bytesUsed += 32 + ALLOCATION_SIZE;
  60. Assert_true(Allocator_bytesAllocated(alloc) == bytesUsed);
  61. Allocator_free(child);
  62. bytesUsed -= 32 + ALLOCATION_SIZE;
  63. bytesUsed -= ALLOCATION_SIZE + ALLOCATOR_SIZE;
  64. Assert_true(Allocator_bytesAllocated(alloc) == bytesUsed);
  65. Allocator_free(alloc);
  66. }
  67. int main()
  68. {
  69. allocatorClone();
  70. structureSizes();
  71. return 0;
  72. }