rendered paste body#include <memory.h>#include <stdio.h>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) { malloc_begin=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->a) 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;}void * realloc(void * ptr, size_t size) { struct Malloc * head = malloc_begin; while (head) { if (head->a==ptr) { struct Malloc * newmem; if (head->size >= size) return head->a; /* no problem */ /* otherwise allocate new and copy over */ newmem = findFirstFree(size); if (!newmem) return NULL; memcpy(newmem->a,head->a,size); free(head->a); return newmem->a; } head=head->next; } fprintf(stderr,"attempt to realloc memory unknown to allocator\n"); return NULL;}int main(void) { void * first; void * second; first = malloc(50); second = malloc(100); printf ("first=%p\n",first); printf ("second=%p\n",second); free(second); free(first); first=malloc(100); second=malloc(50); printf ("first=%p\n",first); printf ("second=%p\n",second); return 0;}