Advertisement
Guest User

GC

a guest
Nov 24th, 2012
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.61 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. struct list_items
  5. {
  6.     struct list_items *next;
  7.     int *data;
  8.     int size;
  9. };
  10.  
  11. struct list_ptrs
  12. {
  13.     struct list_ptrs *next;
  14.     struct list_items *items;
  15. };
  16.  
  17. static struct list_ptrs *spl = NULL;
  18.  
  19. int *alloc_continue(int n)
  20. {
  21.     printf("alloc_continue(%d)\n", n);
  22.     struct list_ptrs *ptr = spl;
  23.     struct list_items *item = malloc(sizeof(struct list_items));
  24.     item->next = ptr->items;
  25.     item->data = malloc(sizeof(int)*n);
  26.     item->size = n;
  27.     ptr->items = item;
  28.     return item->data;
  29. }
  30.  
  31.  
  32. int *alloc_begin(int n)
  33. {
  34.     printf("alloc_begin(%d)\n", n);
  35.     struct list_ptrs *ptr = malloc(sizeof(struct list_ptrs));
  36.     ptr->next = spl;
  37.     ptr->items = NULL;
  38.     spl = ptr;
  39.     return alloc_continue(n);
  40. }
  41.  
  42. void print_spl()
  43. {
  44.     int l = 0;
  45.     struct list_ptrs *ptr = spl;
  46.     while(ptr)
  47.     {
  48.         printf("%d: ", l);
  49.         struct list_items *item = ptr->items;
  50.         while(item)
  51.         {
  52.             printf("%p[%d] ", item->data, item->size);
  53.             item = item->next;
  54.         }
  55.         printf("\n");
  56.         ptr = ptr->next;
  57.         l++;
  58.     }
  59. }
  60.  
  61. void free_block()
  62. {
  63.     struct list_ptrs *ptr = spl;
  64.     if(!ptr)
  65.         return;
  66.     struct list_items *item = ptr->items;
  67.     spl = ptr->next;
  68.     free(ptr);
  69.     printf("Delete: ");
  70.     while(item)
  71.     {
  72.         printf("[%d] ", item->size);
  73.         free(item->data);
  74.         struct list_items *item_tmp = item;
  75.         item = item->next;
  76.         free(item_tmp);
  77.     }
  78.     printf("\n");
  79. }
  80.  
  81. void foo()
  82. {
  83.     int *a1 = alloc_begin(1);
  84.     int *a2 = alloc_continue(2);
  85.     int *a3 = alloc_continue(3);
  86.     {
  87.         int *a4 = alloc_begin(4);
  88.         int *a5 = alloc_continue(5);
  89.         print_spl();
  90.         free_block();
  91.     }
  92.     free_block();
  93. }
  94.  
  95. int main()
  96. {
  97.     foo();
  98.     return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement