I read some pages on how to ask questions, so I hope this is consistent with the standard.
Our professor wants us to create a custom malloc and a free one that uses buddy distribution. Instead of messing around with a bunch, he wants us to just use mmap to request 1 gigabyte of space from the OS:
MAX_MEM = 1 << 30.
void * base = mmap(NULL, MAX_MEM, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, 0, 0);
Each piece of memory should have a header, and if the memory is empty, it indicates the next and previous free fragments through a linked list.
I don’t know how to say: "I want to put this specific data in this particular place." I would suggest that there will be a free fragment in memory:
[Occupancy (1 bit)][Size (7 bits)][prev pointer (8 bytes)][next pointer (8bytes)][junk]
So, let's say that all 1 GiB is free. Pseudocode:
Occupancy = 0; // 0 if empty, 1 if allocated
Size = 0011110; // where size in bytes = 2^Size
next = NULL;
prev = NULL; //note that these are part of a struct called mallocList
, ?
,
int MAX_MEM = 1 << 30;
base = mmap(NULL, MAX_MEM, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, 0, 0);
*((unsigned char*) base) = 0x1E;
struct mallocList* temp;
temp->prev = NULL;
temp->next = NULL;
void* tempaddr = base + 1;
*((struct mallocList*) tempaddr) = *temp;
munmap(base, 1 <<30);
, , ,
printf("%c", *base);
struct mallocList* two;
two->prev = NULL;
two->next = NULL;
tempaddr->next = *two;
,
3.c:37: warning: dereferencing ‘void *’ pointer
3.c:37: error: invalid use of void expression
3.c:41: warning: dereferencing ‘void *’ pointer
3.c:41: error: request for member ‘next’ in something not a structure or union
, - , , .
mymalloc.h:
void *my_buddy_malloc(int size);
void my_free(void *ptr);
struct mallocList
{
struct mallocList *prev;
struct mallocList *next;
} mallocList;