add: free

This commit is contained in:
starnakin 2023-06-18 11:11:23 +02:00
parent cea014d97b
commit 60ca301082
3 changed files with 41 additions and 18 deletions

View File

@ -123,3 +123,34 @@ galloc(size)
split_block(ptr, size);
return (ptr + LOCATION_DATA);
}
merge_blocks(first_block, last_block)
{
local size;
size = last_block - first_block - HEADER_SIZE - PADDING_SIZE * 2;
setup_header(first_block, 0, size, [last_block + LOCATION_NEXT], [first_block + LOCATION_PREV]);
return (first_block);
}
free(ptr)
{
local block;
local prev_block;
local next_block;
local first_block;
local last_block;
block = ptr - LOCATION_DATA;
prev_block = [block + LOCATION_PREV];
if ([prev_block + LOCATION_USED])
first_block = block;
else
first_block = prev_block;
next_block = [block + LOCATION_NEXT];
if ([next_block + LOCATION_USED])
last_block = block;
else
last_block = next_block;
merge_blocks(first_block, last_block);
}

View File

@ -1,10 +1,13 @@
main()
{
local ptr1;
local ptr2;
name = "galloc";
dbg galloc(1);
dbg galloc(1);
dbg galloc(1);
dbg galloc(1);
dbg galloc(1);
ptr1 = galloc(1);
test_str(ptr1, heap + LOCATION_DATA, "");
free(ptr1);
ptr1 = galloc(1);
test_str(ptr1, heap + LOCATION_DATA, "alloc after free");
ptr2 = galloc(1);
}

View File

@ -1,17 +1,6 @@
global name;
putstr(str){
local i;
i = 0;
loop {
if ([str + i] == 0)
return;
wrt [str + i];
i++;
}
}
test(value, reach_value, description)
test_str(value, reach_value, description)
{
putstr(name);
if (value != reach_value)