00001 #ifndef _MULTIMALLOC_H_
00002 #define _MULTIMALLOC_H_
00003
00004 #include <assert.h>
00005
00006 #include <fstream.h>
00007
00008
00009 #include "dynarray.h"
00010 #include "stack.h"
00011
00012
00013 template <class SuperHeap>
00014 class MultiMalloc : public SuperHeap {
00015 public:
00016
00017
00018 MultiMalloc (void) {
00019
00020 }
00021
00022 ~MultiMalloc (void) {
00023
00024 }
00025
00026
00027
00028 int multimalloc (int num, size_t sz, void *& ptr)
00029 {
00030
00031
00032 assert (num > 0);
00033 if (stk.empty()) {
00034 #if 0
00035
00036 ptr = SuperHeap::malloc (sz);
00037 assert (size(ptr) >= sz);
00038 assert (sz >= sizeof(FreeObject *));
00039 FreeObject * p = (FreeObject *) ptr;
00040 for (int i = 1; i < num; i++) {
00041 p->next = (FreeObject *) SuperHeap::malloc (sz);
00042 p = p->next;
00043 assert (size(p) >= sz);
00044 }
00045 p->next = NULL;
00046 #else
00047 size_t sz1 = align(sz + sizeof(double));
00048 ptr = SuperHeap::malloc (num * sz1);
00049 ptr = (double *) ptr + 1;
00050 FreeObject * p = (FreeObject *) ptr;
00051 for (int i = 0; i < num - 1; i++) {
00052 size(p) = sz;
00053 FreeObject * next = (FreeObject *) (((unsigned long) p) + sz1);
00054 p->next = next;
00055 p = p->next;
00056 }
00057 size(p) = sz;
00058 p->next = NULL;
00059 assert (size(p) + ((unsigned long) p) <= ((unsigned long) ptr + num * sz1));
00060 #endif
00061
00062 #ifndef NDEBUG
00063 p = (FreeObject *) ptr;
00064 int c = 0;
00065 while (p != NULL) {
00066 c++;
00067 p = p->next;
00068 }
00069 assert (c == num);
00070 #endif
00071 return num;
00072 } else {
00073
00074 assert (!stk.empty());
00075 np v = stk.pop();
00076
00077 assert (v.num == num);
00078 ptr = v.ptr;
00079 assert (v.num > 0);
00080 assert (size(ptr) >= sz);
00081
00082 return v.num;
00083 }
00084 }
00085
00086
00087 void multifree (int num, void * ptr)
00088 {
00089
00090 np v;
00091
00092 v.num = num;
00093 v.ptr = ptr;
00094 stk.push (v);
00095 }
00096
00097 private:
00098
00099 MultiMalloc (const MultiMalloc&);
00100 MultiMalloc& operator=(const MultiMalloc&);
00101
00102 class np {
00103 public:
00104 int num;
00105 void * ptr;
00106 };
00107
00108 class FreeObject {
00109 public:
00110 FreeObject * next;
00111 };
00112
00113 void * malloc (size_t);
00114 void free (void *);
00115
00116 Stack<np, DynArray<np> > stk;
00117
00118
00119 static inline size_t align (size_t sz) {
00120 return (sz + (sizeof(double) - 1)) & ~(sizeof(double) - 1);
00121 }
00122
00123 };
00124
00125
00126 #endif