To recode the malloc function, I do a sbrk(stack)
where :
void *malloc(size_t size)
{
stack = 0;
while (stack < size)
stack += 4096;
}
I malloc always more than I need then I want to take some of this allocated area of size size
and return it, and if I want to do another malloc after I already have allocated memory so I dont have to do multiple call of sbrk.
How can i do that, i tried to go back with brk(start_of_the_allocated_space)
, sbrk(size)
to have the start and end of the space i need but it segfault.
EDIT:
struct s_block {
size_t size;
struct s_block *next;
struct s_block *prev;
void *start;
void *end;
}
Here is my structure. Then I have a func who create a block
struct s_block *create_block(size_t size, unsigned int stack)
{
struct s_block *block;
block = sbrk(sizeof(s_block));
block->start = sbrk(stack);
block->size = stack;
block->end = sbrk(0);
block->next = set_free_space(size, block);
block->size -= size;
block->next->prev = block;
block->prev = NULL;
return (block->next);
}
struct s_block *set_free_space(size_t size, struct s_block *block)
{
struct s_block new_block;
new_block = sbrk(sizeof(s_block));
new_block->start = block->start;
new_block->next = NULL;
new_block->size = size;
new_block->end = ???; // this is where I want to split the first sbrk
// I tried new_block->end = new_block->start + size; but it doesn't work either
block->start = new_block->end + 1; // and i set the new start of the big block at the end of the one i use
return (new_block);
}