ft_malloc/srcs/bonus_utils.c

85 lines
3 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* bonus_utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: thrieg <thrieg@student.42mulhouse.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/11/28 16:42:13 by thrieg #+# #+# */
/* Updated: 2025/12/13 04:42:15 by thrieg ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/ft_malloc.h"
#include "../libft/ft_printf/ft_printf.h"
// bytes_per_line has to be a power of 2
static void hexdump_block(void *addr, size_t size, size_t bytes_per_Line)
{
unsigned char *p = (unsigned char *)addr;
uintptr_t start = (uintptr_t)p;
uintptr_t end = start + size;
// align down to bytes_per_Line bytes
uintptr_t line_start = start & ~(uintptr_t)(bytes_per_Line - 1);
while (line_start < end)
{
ft_printf("%p: ", (void *)line_start);
for (size_t i = 0; i < bytes_per_Line; ++i)
{
uintptr_t pos = line_start + (uintptr_t)i;
if (pos < start || pos >= end)
{
// outside the block; print spaces to keep alignment
ft_printf(" ");
}
else
{
unsigned char byte = *(unsigned char *)pos;
ft_printf("%02x ", (unsigned int)byte);
}
}
ft_printf("\n");
line_start += bytes_per_Line;
}
}
void print_zone(t_zone *zone, bool hexdump_free_zones)
{
ft_printf("--------------------------------\n");
ft_printf("new %s zone:\n", zone->type == E_TINY ? "tiny" : (zone->type == E_SMALL ? "small" : "large"));
ft_printf("size: %u\n", (unsigned int)zone->size);
ft_printf("--------------------------------\n");
char *zone_end = (char *)zone + zone->size;
t_header *header = (t_header *)(zone + 1);
while ((char *)header + sizeof(t_header) <= zone_end)
{
ft_printf("--------------------------------\n");
ft_printf("new %s header:\n", header->occupied ? "allocated" : "free");
ft_printf("size: %u\n", (unsigned int)header->size);
ft_printf("--------------------------------\n");
if (header->occupied || hexdump_free_zones)
hexdump_block(header + 1, header->size, 16);
header = (t_header *)((char *)(header + 1) + header->size);
}
}
void print_all_zones(t_zone *first_zone, bool hexdump_free_zones)
{
while (first_zone)
{
print_zone(first_zone, hexdump_free_zones);
first_zone = first_zone->next;
}
}
void show_alloc_mem_ex(bool hexdump_free_zones)
{
print_all_zones(g_state.tiny_zone, hexdump_free_zones);
print_all_zones(g_state.small_zone, hexdump_free_zones);
print_all_zones(g_state.large_zone, hexdump_free_zones);
}