/* malloc3.c (emx+gcc) */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 4

static char *check[] =
{
  "ok", "empty", "bad begin", "bad node", "bad end", "bad rover"
};


int main (void)
{
  char buf[256], *p;
  void *table[N], *v;
  int idx;
  int i, n;

  for (i = 0; i < N; ++i)
    table[i] = NULL;
  idx = 0;
  for (;;)
    {
      n = (int)sbrk (0);
      printf ("sbrk = 0x%x\n", n);
      for (i = 0; i < N; ++i)
        {
          if (i == idx) putchar ('*');
          printf ("%d:0x%x  ", i, (int)table[i]);
        }
      printf ("\n? ");
      if (fgets (buf, sizeof (buf), stdin) == NULL)
        return 0;
      p = strchr (buf, '\n');
      if (p != NULL) *p = 0;
      if (buf[0] == '?')
        {
          puts ("?    help");
          puts ("q    quit");
          puts ("f    free");
          puts ("c    check");
          puts ("r#   realloc(#)");
          puts ("#    malloc(#)");
          puts ("     next slot");
        }
      else if (buf[0] == 'q')
        return 0;
      else if (buf[0] == 'f')
        {
          printf ("free\n");
          free (table[idx]); table[idx] = NULL;
        }
      else if (buf[0] == 'c')
        printf ("%s\n", check[_heapset ('/')]);
      else if (buf[0] == 0)
        idx = (idx+1)%N;
      else
        {
          p = buf;
          if (*p == 'r')
            ++p;
          i = atoi (p);
          if (buf[0] == 'r')
            v = realloc (table[idx], i);
          else
            v = malloc (i);
          if (v == NULL)
            printf ("%s() failed\n", (buf[0] == 'r' ? "realloc" : "malloc"));
          else
            {
              if ((long)v & 3)
                printf ("Wrong alignment!\n");
              table[idx] = v;
              memset (v, '*', i);
            }
        }
    }
}
