/* malloc2.c */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <umalloc.h>

static char do_sbrk;


static void show_stat (void)
{
  _HEAPSTATS stats;

  assert (_ustats (_RUNTIME_HEAP, &stats) == 0);
  printf ("provided=%lu, used=%lu, segments=%lu\n",
          stats._provided, stats._used, stats._segments);
}


static void recurse (int level)
{
  void *p;

  if (level >= 200)
    {
      show_stat ();
      return;
    }

  if (level == 100 && do_sbrk)
    assert (sbrk (1) != (void *)-1);
  p = malloc (700);
  assert (p != NULL);
  assert (_heapchk () == _HEAPOK);
  recurse (level + 1);
  free (p);
  assert (_heapchk () == _HEAPOK);
  if (level == 50 || level == 2 || level == 0)
    {
      show_stat ();
      assert (_heapmin () == 0);
      assert (_heapchk () == _HEAPOK);
      show_stat ();
    }
}


int main (int argc, char *argv[])
{
  if (argc == 2 && strcmp (argv[1], "-b") == 0)
    do_sbrk = 1;
  else if (argc != 1)
    {
      puts ("Usage: malloc2 [-b]");
      exit (1);
    }
  recurse (0);
  return 0;
}
