Advertisement
Looong

Lab 8 - OS - Allocator

Nov 26th, 2015
473
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.62 KB | None | 0 0
  1. #include <unistd.h>
  2.  
  3. struct boundary_t
  4. {
  5.   boundary_t *next;
  6.   boundary_t *previous;
  7.   size_t size;
  8. };
  9.  
  10. boundary_t *head = 0;
  11.  
  12. void *malloc(size_t size)
  13. {
  14.   if (!head) {
  15.     head = (boundary_t *) sbrk(sizeof(boundary_t));
  16.     head->next = 0;
  17.     head->previous = 0;
  18.     head->size = 0;
  19.   };
  20.  
  21.   boundary_t *b = head;
  22.   size_t needed_size = sizeof(boundary_t) + size;
  23.  
  24.   for (; b->next; b = b->next) {
  25.     if (!b->size) {
  26.       size_t free_size = ((size_t) b->next) - ((size_t) (b + 1));
  27.  
  28.       if (free_size >= needed_size) {
  29.         b->size = size;
  30.         boundary_t *next = b->next;
  31.         b->next = (boundary_t *)(((size_t) (b + 1)) + size);
  32.         b->next->next = next;
  33.         b->next->previous = b;
  34.         b->next->size = 0;
  35.  
  36.         return (void *) (b + 1);
  37.       };
  38.     };
  39.   };
  40.  
  41.   void *ptr = sbrk(size);
  42.   b->next = (boundary_t *) sbrk(sizeof(boundary_t));
  43.   b->next->next = 0;
  44.   b->next->previous = b;
  45.   b->next->size = 0;
  46.  
  47.   return ptr;
  48. };
  49.  
  50. void free(void *ptr)
  51. {
  52.   if (!head)
  53.     return;
  54.  
  55.   boundary_t *b = head;
  56.  
  57.   for (; b; b = b->next) {
  58.     if (((void *) (b + 1)) == ptr) {
  59.       if (!b->size)
  60.         return;
  61.  
  62.       if (b == head) {
  63.         head->size = 0;
  64.         head->next = head->next->next;
  65.         head->next->previous = head;
  66.  
  67.         return;
  68.       };
  69.  
  70.       if (b->next->next) {
  71.         head->next->next->previous = head->previous;
  72.         head->previous->next = head->next->next;
  73.  
  74.         return;
  75.       };
  76.  
  77.       head->next->previous = head->previous;
  78.       head->previous = head->next;
  79.  
  80.       return;
  81.     };
  82.   };
  83. };
  84.  
  85. int main()
  86. {
  87.   return 0;
  88. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement