/* ============================================================= */ /* Jean-Michel RICHER - 2008 - */ /* ============================================================= */ #include "multi_alloc.h" static int Struct_index=0; static Struct *Struct_list=NULL; /** * allocate a new object * a block of objects is allocated and linked * */ Struct *Struct_malloc() { Struct *ptr=Struct_list; // no more objects are available, then create a new block if (ptr==NULL) { int i; ptr=Struct_list=(Struct *)calloc(BLOCK_SIZE,sizeof(Struct)); for (i=0;i<BLOCK_SIZE-1;++i) { ptr[i].next=&ptr[i+1]; } ptr[i].next=NULL; } Struct_list=ptr->next; return ptr; } void Struct_free(Struct *s) { s->next=Struct_list; Struct_list=s; } // ------------------------------------------------- int main() { const int N=78; Struct **array; int sum=0; int i; array=(Struct **)calloc(N,sizeof(Struct *)); // allocate first time and fill for (i=0;i<N;++i) { array[i]=(Struct *)Struct_malloc(); array[i]->number=i; } for (i=0;i<N;++i) { printf("element %d = %d\n", i, array[i]->number); sum+=array[i]->number; } printf("sum = %d (expected value 3003)\n",sum); // free for (i=0;i<N;++i) { Struct_free(array[i]); } // then allocate a second time for (i=0;i<N;++i) { array[i]=(Struct *)Struct_malloc(); } sum=0; for (i=0;i<N;++i) { printf("element %d = %d\n", i, array[i]->number); sum+=array[i]->number; } printf("sum = %d (expected value 3003)\n",sum); return 0; }