Organizes a series of allocated spaces in the form of an idle list, and only supports built-in types in this program. Just a simple allocation and recycling is achieved.
#include <iostream> #include <assert.h> #include <stdlib.h>using namespace Std;int const max=100; struct block{block *next; Block *addr; Explicit block (int _size): Next (NULL) {addr= (block*) malloc (_size);} ~block () {delete Next;delete addr;next=null;addr=null;}}; struct list{block *freelist; Block *used; List (): FreeList (NULL), Used (null) {} ~list () {delete freelist;delete used;}}; Class mypool{public:explicit mypool (int requester_size): Size_type (requester_size) {pool =new list; Pool->freelist=new block (size_type); Block *head=pool->freelist; for (int i=0;i<10;i++) {block *p=new block (size_type); head->next=p; head=head->next; } head = pool->freelist; } void *alloc () {block *alc; Block *prev=pool->freelist; cout<< "Start" <<pool->freeList<<endl; if (prev!=null) ALC=prev->next; else return NULL; if (prev->next==null) {alc=prev; Prev=null; return ALC; } while (Alc->next!=null) {prev=prev->next; alc=prev->next; prev->next=null;//move out of the allocated chunk//cout<<alc<<endl; return ALC; } void Dealc (void* addr) {block *head=pool->freelist; while (head->next!=null) {head=head->next; } head->next= (block*) (addr); head->next->next=null; } ~mypool () {delete pool;} Private:int Size_type; List *pool; };int Main () {Mypool my (sizeof (int)); int *a= (int*) my.alloc (); *a=5; cout<<a<< "" <<*a<<endl; My.dealc (a); cout<<a<< "" <<*a<<endl; return 0;}
Simple memory pools implemented by C + +