#define MALLOC_MODULE
#include "octi.h"

//magic to make malloc exit with a fatal error if it fails
#ifdef DEBUG_MALLOCS

#include <stdio.h>

typedef struct MALLOC {
 struct MALLOC *prev;
 void *ptr;
} MALLOC;

MALLOC *malloc_list=0;

int get_n_mallocs() {
 MALLOC *m=malloc_list;
 int n=0;
 while (m) {
  m=m->prev;
  n++;
 }
 return n;
}

void check_mallocs() {
 fprintf(stderr,"Number of mallocs not freed: %d\n\n",get_n_mallocs());
}

void *malloc_e(size_t size) {
 static unsigned char virgin=1;
 if (virgin) {
  virgin=0;
  atexit(check_mallocs);
 }
 {
  void *p=malloc(size);
  if (p) {
   MALLOC *new_malloc=malloc(sizeof(MALLOC));
   new_malloc->prev=malloc_list;
   new_malloc->ptr=p;
   malloc_list=new_malloc;
   return p;
  }
  allegro_exit();
  allegro_message("Out of memory.\n\n");
  exit(1);
 }
}

void free_e(void *ptr) {
 free(ptr);
 {
  MALLOC **free_malloc=&malloc_list;
  while (*free_malloc) {
   if (ptr==(*free_malloc)->ptr) {
    MALLOC *malloc_removed=*free_malloc;
    *free_malloc=malloc_removed->prev;
    free(malloc_removed);
    return;
   }
   free_malloc=&(*free_malloc)->prev;
  }
 }
}
#else
#undef malloc
void *malloc_e(size_t size) {
 void *p=malloc(size);
 if (p) return p;
 allegro_exit();
 allegro_message("Out of memory.\n\n");
 exit(1);
}
#endif

