aboutsummaryrefslogtreecommitdiffstats
path: root/src/show_alloc_mem.c
blob: 6fd5e37b20d1f7b82cab44b0896b2cfe5574eb41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
 * @file   show_alloc_mem.c
 * @brief  Print every allocated zone and block to stdout.
 */

#include "libft.h"
#include "malloc.h"
#include "malloc_internal.h"

static void
_s_put_ptr (void *ptr)
{
  const char hex[] = "0123456789abcdef";
  char buf[20];
  unsigned long value;
  int i;

  value = (unsigned long)ptr;
  i = (int)sizeof (buf);
  while (value)
    {
      buf[--i] = hex[value % 16];
      value /= 16;
    }
  buf[--i] = 'x';
  buf[--i] = '0';
  ft_putstr_fd (buf + i, 1);
}

static void
_s_put_size (size_t n)
{
  if (n >= 10)
    _s_put_size (n / 10);
  ft_putchar_fd ('0' + (n % 10), 1);
}

static size_t
_s_print_zone (char *label, t_zone *zone)
{
  t_chunk *chunk;
  void *start;
  void *end;
  size_t total;

  total = 0;
  while (zone)
    {
      ft_putstr_fd (label, 1);
      ft_putstr_fd (" : ", 1);
      _s_put_ptr (zone);
      ft_putchar_fd ('\n', 1);
      chunk = (t_chunk *)((char *)zone + ALIGN (sizeof (t_zone)));
      while (chunk)
        {
          if (!chunk->is_free)
            {
              start = (char *)chunk + ALIGN (sizeof (t_chunk));
              end = (char *)start + chunk->size;
              _s_put_ptr (start);
              ft_putstr_fd (" - ", 1);
              _s_put_ptr (end);
              ft_putstr_fd (" : ", 1);
              _s_put_size (chunk->size);
              ft_putendl_fd (" bytes", 1);
              total += chunk->size;
            }
          chunk = chunk->next;
        }
      zone = zone->next;
    }
  return (total);
}

void
show_alloc_mem (void)
{
  size_t total;

  total = 0;
  total += _s_print_zone ("TINY", g_heap.tiny);
  total += _s_print_zone ("SMALL", g_heap.small);
  total += _s_print_zone ("LARGE", g_heap.large);
  ft_putstr_fd ("Total : ", 1);
  _s_put_size (total);
  ft_putendl_fd (" bytes", 1);
}