Write your own malloc

I am writing my own malloc () and I already understood the following

struct myblock { struct myblock *next; struct myblock *prev; int isFree; unsigned availablesize; char *buffer; } 

and the space #define MEM_BUFFER (1024), which will be "my bar". and if I'm not mistaken, I will have

 char *array[MEM_BUFFER]; 

to have an array of 1024 bytes (kindly correct me if I am wrong).

As we know, MEM_BUFFER will also contain the matadata of the occupied space. I'm a little confused on how to get started.

This is my main question. Should the structure be assigned to an array for each distribution request (if so, from an array of struct char?).

Do I have to process a double linked list on the heap and bypass sizeof (myblock) bytes from the array.

I have been thinking about this decision for the past 2 days, and I'm still confused.

+4
source share
1 answer

No,

 char *array[MEM_BUFFER]; 

is not an array of 1024 bytes (unless MEM_BUFFER is set to 1024 / sizeof (char *) ). This is an array of MEM_BUFFER character MEM_BUFFER .

You just need to:

 char array[MEM_BUFFER]; 

although the best name might be heap_space .

To make it composed of blocks, you will need an additional pointer, which is the first block:

 struct myblock *heap = (struct myblock *) heap_space; 

Then you can initialize this:

 heap->next = NULL; heap->prev = NULL; heap->isFree = 1; heap->availablesize = sizeof heap_space - sizeof *heap; 

Not sure what to do struct myblock.buffer , I put the blocks inside the heap so that the user memory for the block is in (void *) (block + 1) ;

+6
source

Source: https://habr.com/ru/post/1490443/


All Articles