#include "Memory.h" #define NULL 0 struct Malloc { void *a; struct Malloc *next; int size; int isfree; }; struct Malloc *malloc_begin = NULL; /* find first free region large enough */ struct Malloc* findFirstFree(size_t size) { struct Malloc * head = malloc_begin; struct Malloc * prev = NULL; if (!head) { head=sbrk(sizeof(struct Malloc)); if (!head) return NULL; head->a=sbrk(size); if (!head->a) return NULL; head->next=NULL; head->size=size; head->isfree=0; return head; } while (head) { if (head->isfree && head->size >= size) { return head; } prev=head; head=head->next; } /* not found, so allocate */ prev->next=head=sbrk(sizeof(struct Malloc)); if (!head) return NULL; head->a=sbrk(size); if (!head->) return NULL; head->size=size; head->isfree=0; return head; } void* calloc(size_t nmemb, size_t size){ struct Malloc * mem = findFirstFree(nmemb*size); if (!mem) return NULL; /* TODO: clear memory */ return mem->a; } void* malloc(size_t size){ struct Malloc * mem = findFirstFree(size); if (!mem) return NULL; return mem->a; } void free(void *ptr){ struct Malloc * head = malloc_begin; while (head) { if (head->a==ptr) { head->isfree=1; return; } head=head->next; } fprintf(stderr,"attempt to free memory unknown to allocator\n"); return; }