feat: free (untested)

This commit is contained in:
gbrochar 2025-07-11 14:49:29 +02:00
parent 912064ae31
commit 36dc194c28
2 changed files with 27 additions and 1 deletions

1
main.c
View File

@ -9,6 +9,7 @@ int main(int argc, char **argv) {
size = (rand() & 0x7ff) | 0xf00000;
arr = (int *)ft_malloc(size * sizeof(int));
printf ("arr %d addr: %p arr size: %zu\n", i, arr, size);
free(arr);
}
show_alloc_sizes();
return 0;

View File

@ -2,6 +2,31 @@
void free(void *ptr) {
pthread_mutex_lock(&g_malloc_mutex);
(void)ptr;
t_block *block = (t_block *)((char *)ptr - sizeof(t_block));
if (block->size < g_zones.small_block_max_size) {
block->free = 1;
} else {
t_block *curr = g_zones.large_blocks;
if (curr == NULL) {
pthread_mutex_unlock(&g_malloc_mutex);
return;
}
if ((char *)curr + sizeof(t_block) == (char *)ptr) {
g_zones.large_blocks = curr->next;
munmap((char *)ptr - sizeof(t_block) - (16 - sizeof(t_block) % 16), curr->size + sizeof(t_block) + (16 - sizeof(t_block) % 16));
pthread_mutex_unlock(&g_malloc_mutex);
return;
}
while ((char *)curr->next + sizeof(t_block) != (char *)ptr) {
curr = curr->next;
if (curr == NULL) {
pthread_mutex_unlock(&g_malloc_mutex);
return;
}
}
t_block *to_free = curr->next;
curr->next = curr->next->next;
munmap((char *)ptr - sizeof(t_block) - (16 - sizeof(t_block) % 16), to_free->size + sizeof(t_block) + (16 - sizeof(t_block) % 16));
}
pthread_mutex_unlock(&g_malloc_mutex);
}