#include <stdio.h>
#include <inttypes.h>
#define PAGE_SIZE 16
struct page_t
{
struct page_t *next;
int value;
};
typedef struct page_t page_t;
uint8_t memory[1 << 16]; // 64K should be enough for anyone
page_t *next_page = (page_t *)memory;
page_t *free_pages = 0;
page_t *kalloc_frame()
{
page_t *temp;
if (free_pages == 0)
{
temp = next_page; next_page += PAGE_SIZE;
}
else
{
temp = free_pages; free_pages = free_pages->next;
}
return temp;
}
void kfree_frame(page_t *page)
{
page->next = free_pages; free_pages = page;
}
int main(void) {
page_t *page1, *page2;
printf("next_page = %p, free_pages = %p\n", next_page
, free_pages
);
page1 = kalloc_frame();
page2 = kalloc_frame();
printf("page1 = %p, page2 = %p\n", page1
, page2
);
kfree_frame(page1);
printf("next_page = %p, free_pages = %p\n", next_page
, free_pages
);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxpbnR0eXBlcy5oPgoKI2RlZmluZSBQQUdFX1NJWkUgMTYKCnN0cnVjdCBwYWdlX3QKewoJc3RydWN0IHBhZ2VfdCAqbmV4dDsKCWludCB2YWx1ZTsKfTsKdHlwZWRlZiBzdHJ1Y3QgcGFnZV90IHBhZ2VfdDsKCnVpbnQ4X3QgbWVtb3J5WzEgPDwgMTZdOyAvLyA2NEsgc2hvdWxkIGJlIGVub3VnaCBmb3IgYW55b25lCgpwYWdlX3QgKm5leHRfcGFnZSA9IChwYWdlX3QgKiltZW1vcnk7CnBhZ2VfdCAqZnJlZV9wYWdlcyA9IDA7CgpwYWdlX3QgKmthbGxvY19mcmFtZSgpCnsKCXBhZ2VfdCAqdGVtcDsKCWlmIChmcmVlX3BhZ2VzID09IDApCgl7CgkJdGVtcCA9IG5leHRfcGFnZTsgbmV4dF9wYWdlICs9IFBBR0VfU0laRTsKCX0KCWVsc2UKCXsKCQl0ZW1wID0gZnJlZV9wYWdlczsgZnJlZV9wYWdlcyA9IGZyZWVfcGFnZXMtPm5leHQ7IAoJfQoJcmV0dXJuIHRlbXA7Cn0K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