Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "mem.h"
- #include <stdio.h>
- #define BASE_HEAP_SIZE 2000
- #define HEAP_EXPANSION_SIZE 1000
- int memory_allocated = 0;
- int heap_size = 0;
- char *heap = 0;
- int heap_offset;
- void mem_error()
- {
- if(heap != 0)
- {
- printf("Dumping Memory To File\n");
- mem_dump("lastrun.dump");
- printf("Freeing Heap\n");
- free(heap);
- }
- exit(1);
- }
- void mem_initialize()
- {
- heap = malloc(BASE_HEAP_SIZE);
- memset(heap,0,BASE_HEAP_SIZE);
- heap_size = BASE_HEAP_SIZE;
- }
- void mem_dump(const char *file)
- {
- FILE *f = fopen(file, "wb");
- if(!f) return;
- fwrite(heap,1,memory_allocated,f);
- fclose(f);
- }
- int mem_increaseHeapSize()
- {
- }
- void *mem_alloc(int size)
- {
- int remain = heap_size - memory_allocated;
- int position = 0;
- if(size > 127)
- {
- printf("Unable to allocate memory[%i]\
- , max allocation size is 127",size);
- mem_error();
- }
- if(remain <= 0 || size > remain)
- {
- printf("Unable to allocate memory[%i]\
- , heap is full\n",size);
- mem_error();
- }
- while(position < heap_size)
- {
- char ident = (char) *(heap + position);
- char iSize = ident & 127;
- char bAllocated = ident & 128;
- if(!bAllocated)
- {
- if(iSize == 0 || iSize == size)
- {
- *(heap + position) = (size & 127) | 128;
- memory_allocated += size;
- return (heap + position + 1);
- }
- }
- position += iSize + 1;
- }
- printf("Unable to allocate memory, end of heap\n");
- mem_error();
- return 0;
- }
- void *mem_put(void *o, int size)
- {
- void *mem = mem_alloc(size);
- memcpy(mem,o,size);
- return mem;
- }
- void mem_free(void *mem)
- {
- int addr = mem - (void *) heap;
- char ident = (char) *(heap + addr - 1);
- char iSize = ident & 127;
- char bAllocated = ident & 128;
- if(!bAllocated) return;
- printf("%i SIZE\n",iSize);
- memory_allocated -= iSize;
- *(heap + addr - 1) = ident & 127;
- }
- void mem_destroy()
- {
- free(heap);
- }
- int total_allocated()
- {
- return memory_allocated;
- }
Add Comment
Please, Sign In to add comment