fork download
  1. #include <stdio.h>
  2. #include <inttypes.h>
  3.  
  4. #define PAGE_SIZE 16
  5.  
  6. struct page_t
  7. {
  8. struct page_t *next;
  9. int value;
  10. };
  11. typedef struct page_t page_t;
  12.  
  13. uint8_t memory[1 << 16]; // 64K should be enough for anyone
  14.  
  15. page_t *next_page = (page_t *)memory;
  16. page_t *free_pages = 0;
  17.  
  18. page_t *kalloc_frame()
  19. {
  20. page_t *temp;
  21. if (free_pages == 0)
  22. {
  23. temp = next_page; next_page += PAGE_SIZE;
  24. }
  25. else
  26. {
  27. temp = free_pages; free_pages = free_pages->next;
  28. }
  29. return temp;
  30. }
  31.  
  32. void kfree_frame(page_t *page)
  33. {
  34. page->next = free_pages; free_pages = page;
  35. }
  36.  
  37. int main(void) {
  38. page_t *page1, *page2;
  39.  
  40. printf("next_page = %p, free_pages = %p\n", next_page, free_pages);
  41.  
  42. page1 = kalloc_frame();
  43. page2 = kalloc_frame();
  44. printf("page1 = %p, page2 = %p\n", page1, page2);
  45.  
  46. kfree_frame(page1);
  47.  
  48. printf("next_page = %p, free_pages = %p\n", next_page, free_pages);
  49.  
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0.01s 5360KB
stdin
Standard input is empty
stdout
next_page = 0x55577f782040, free_pages = (nil)
page1 = 0x55577f782040, page2 = 0x55577f782140
next_page = 0x55577f782240, free_pages = 0x55577f782040