Advertisement
Guest User

Untitled

a guest
Mar 3rd, 2015
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. /*
  2. * Nabil Fadili
  3. * TCSS 333A
  4. * March 3 2014
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include "mallok.h"
  10.  
  11.  
  12. static memBlock *mainBlock;
  13. static memBlock *front;
  14. static int totalBlocks = 0; //counter for memBlocks not including mainBlock
  15.  
  16. void create_pool(int size) {
  17. mainBlock = malloc(size);
  18. mainBlock->start = mainBlock;
  19. mainBlock->size = size;
  20. mainBlock->free = TRUE;
  21. mainBlock->next = NULL;
  22. mainBlock->prev = NULL;
  23. front = mainBlock;
  24. }
  25.  
  26. void *my_malloc(int size) {
  27. memBlock ptr = front;
  28. while(!ptr->free) {
  29. ptr = ptr->next;
  30. }
  31. //if (ptr->)
  32. if (size > mainBlock->size) {
  33. printf("Not enough memory to allocate.\n");
  34. return NULL;
  35. }
  36. if (size <= mainBlock->size) { //greater than OR equal. keep an eye on this
  37. memBlock *newBlock = malloc(sizeof(memBlock));
  38.  
  39. newBlock->start = mainBlock->start;
  40. mainBlock->start += size;
  41.  
  42. mainBlock->size -= size;
  43.  
  44. newBlock->size = size;
  45. newBlock->free = FALSE;
  46.  
  47. newBlock->next = mainBlock;
  48. newBlock->prev = NULL;
  49. mainBlock->prev = newBlock;
  50.  
  51. totalBlocks++; //increment count of used blocks
  52.  
  53. printf("Memory allocated. Bytes left = %d\n", mainBlock->size);
  54. printf("Total blocks = %d\n", totalBlocks);
  55.  
  56. front = newBlock;
  57.  
  58. return newBlock;
  59. }
  60. //return NULL;
  61. }
  62. void my_free(void *block) {
  63. memBlock *freeBlock = block;
  64. int flag = FALSE;
  65.  
  66. freeBlock->free = TRUE;
  67.  
  68. if (freeBlock->prev->free) {
  69. freeBlock->prev->size += freeBlock->size;
  70. freeBlock->prev->next = freeBlock->next;
  71. freeBlock->next->prev = freeBlock->prev;
  72. flag = TRUE;
  73. }
  74. if (freeBlock->next->free) {
  75. if (flag) {
  76. freeBlock->prev->size += freeBlock->next->size;
  77. freeBlock->prev->next = freeBlock->next->next;
  78. freeBlock->next->next->prev = freeBlock->prev;
  79. }
  80. else {
  81. freeBlock->size += freeBlock->next->size;
  82. freeBlock->next = freeBlock->next->next;
  83. freeBlock->next->prev = freeBlock;
  84. }
  85. }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement