mfunyu / malloc

Find out the workings behind optimum memory management and recode it, as well as free and realloc.
2 stars 0 forks source link

[impl] `show_alloc_mem` check overflow #41

Closed mfunyu closed 7 months ago

mfunyu commented 7 months ago
#include "malloc_internal.h"
#include "ft_printf.h"

static size_t   sum_overflow_check(size_t dst, size_t add, bool *overflow)
{
    if (*overflow)
        return (dst);
    if (dst + add >= dst)
        return (dst + add);
    *overflow = true;
    return (dst);
}

static size_t   _print_large_simple(t_mmap_chunk *lst, bool *overflow)
{
    size_t  sum;

    sum = 0;
    while (lst)
    {
        ft_printf("LARGE : %p\n", lst);
        ft_printf("%p ~ %p : %zu bytes\n", MEM(lst), MEM(lst) + CHUNKSIZE(lst), CHUNKSIZE(lst));
        sum = sum_overflow_check(sum, CHUNKSIZE(lst), overflow);
        lst = lst->fd;
    }
    return (sum);
}

static size_t   _print_malloc_simple(char *zone, t_magazine magazine, bool *overflow)
{
    t_malloc_chunk  *chunk;
    size_t          sum;
    size_t          size;

    sum = 0;
    chunk = magazine.regions;
    ft_printf("%s : %p\n", zone, chunk);
    while (!IS_FOOTER(chunk))
    {
        if (IS_ALLOCED(chunk))
        {
            size = ALLOCSIZE(chunk);
            ft_printf("%p ~ %p : %zu bytes\n", MEM(chunk), MEM(chunk) + size, size);
            sum = sum_overflow_check(sum, size, overflow);
        }
        chunk = NEXTCHUNK(chunk);
    }
    return (sum);
}

void    show_alloc_mem()
{
    size_t  total;
    size_t  sum;
    bool    overflow;

    total = 0;
    overflow = false;
    sum = _print_malloc_simple("TINY", g_malloc.tiny_magazine, &overflow);
    total = sum_overflow_check(total, sum, &overflow);
    sum = _print_malloc_simple("SMALL", g_malloc.small_magazine, &overflow);
    total = sum_overflow_check(total, sum, &overflow);
    sum = _print_large_simple(g_malloc.large_allocations, &overflow);
    total = sum_overflow_check(total, sum, &overflow);
    if (overflow)
        ft_printf("TOTAL : over %zu bytes\n", SIZE_MAX);
    else
        ft_printf("TOTAL : %zu bytes\n", total);
}
mfunyu commented 7 months ago

mmap will fail before reaching over SIZE_MAX allocations