test_for_memory_space_aware.c 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4. #include <dmmlib/initialize_allocator.h>
  5. #include <dmmlib/dmmlib.h>
  6. #include <dmm_config.h>
  7. #define ALLOCATOR_SIZE 16*1024*sizeof(char)
  8. #define cmalloc(size) custom_ahmalloc(&systemallocator, &systemallocator.heaps[0], (size_t) size)
  9. #define cfree(ptr) custom_ahfree(&systemallocator, &systemallocator.heaps[0], ptr)
  10. int main(void) {
  11. allocator_t systemallocator;
  12. void *block_from_malloc;
  13. void *p1, *p2, *p3;
  14. block_from_malloc = malloc(ALLOCATOR_SIZE);
  15. initialize_allocator(&systemallocator, block_from_malloc, ALLOCATOR_SIZE);
  16. /* Testing a best-fit, w/o fixed lists allocator */
  17. /* Test 1: Check is a block can be reused if free'd before. */
  18. printf("Test 1: Check is a block can be reused if free'd before.\n");
  19. p1 = cmalloc(1024);
  20. cfree(p1);
  21. /* Check if the block is taken back */
  22. p2 = cmalloc(1024);
  23. assert( p2 == p1 );
  24. cfree(p2);
  25. printf("Test 1: Success.\n");
  26. /* Test 2: Check if best fit on LIFO works */
  27. printf("Test 2: Check if best fit on LIFO works.\n");
  28. /* Allocate two memory blocks of 1024 and 432 bytes */
  29. p1 = cmalloc(1024);
  30. p2 = cmalloc(432);
  31. /* Make them free */
  32. cfree(p2);
  33. cfree(p1);
  34. /* Pray that the following malloc is going to use the second block of the
  35. * free list.
  36. */
  37. p3 = cmalloc(432);
  38. assert( p3 == p2 );
  39. cfree(p3);
  40. printf("Test 2: Success.\n");
  41. /* Test 3: Check if splitting works
  42. *
  43. * Note: Splitting is checked for fixed-sized splitting or the
  44. * initial value of variable-sized splitting.
  45. */
  46. #ifdef MIN_SPLITTING_SIZE
  47. printf("Test 3: Check if splitting works.\n");
  48. /* Reset everything */
  49. initialize_allocator(&systemallocator, block_from_malloc, ALLOCATOR_SIZE);
  50. if(1000 - MIN_SPLITTING_SIZE > 0 && MIN_SPLITTING_SIZE - 50 > 0) {
  51. p1 = cmalloc(1000);
  52. cfree(p1);
  53. /* This would go to the first block and split it */
  54. p1 = cmalloc(1000 - MIN_SPLITTING_SIZE - 50); /* 50 to compansate safely the
  55. header size */
  56. /* This goes to the third block */
  57. p2 = cmalloc(432);
  58. /* Check if the split free block is used */
  59. p3 = cmalloc(MIN_SPLITTING_SIZE - 50); /* 50 to compansate safely the
  60. header size */
  61. assert( p3 > p1 ); /* Small sanity check */
  62. assert( p3 < p2 );
  63. printf("Test 3: Success.\n");
  64. } else {
  65. printf("Please check maximum splitting size and try to fit it between 50 and 1000 bytes.\n");
  66. }
  67. #endif /* MIN_SPLITTING_SIZE */
  68. free(block_from_malloc);
  69. return 0;
  70. }