Guest User

Untitled

a guest
May 20th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. #include "mem.h"
  2. #include <stdio.h>
  3.  
  4. #define BASE_HEAP_SIZE 2000
  5. #define HEAP_EXPANSION_SIZE 1000
  6.  
  7. int memory_allocated = 0;
  8. int heap_size = 0;
  9. char *heap = 0;
  10. int heap_offset;
  11.  
  12. void mem_error()
  13. {
  14. if(heap != 0)
  15. {
  16. printf("Dumping Memory To File\n");
  17. mem_dump("lastrun.dump");
  18. printf("Freeing Heap\n");
  19. free(heap);
  20. }
  21. exit(1);
  22. }
  23.  
  24. void mem_initialize()
  25. {
  26. heap = malloc(BASE_HEAP_SIZE);
  27. memset(heap,0,BASE_HEAP_SIZE);
  28. heap_size = BASE_HEAP_SIZE;
  29. }
  30.  
  31. void mem_dump(const char *file)
  32. {
  33. FILE *f = fopen(file, "wb");
  34. if(!f) return;
  35.  
  36. fwrite(heap,1,memory_allocated,f);
  37.  
  38. fclose(f);
  39. }
  40.  
  41. int mem_increaseHeapSize()
  42. {
  43.  
  44. }
  45.  
  46. void *mem_alloc(int size)
  47. {
  48. int remain = heap_size - memory_allocated;
  49. int position = 0;
  50. if(size > 127)
  51. {
  52. printf("Unable to allocate memory[%i]\
  53. , max allocation size is 127",size);
  54. mem_error();
  55. }
  56. if(remain <= 0 || size > remain)
  57. {
  58. printf("Unable to allocate memory[%i]\
  59. , heap is full\n",size);
  60. mem_error();
  61. }
  62. while(position < heap_size)
  63. {
  64. char ident = (char) *(heap + position);
  65. char iSize = ident & 127;
  66. char bAllocated = ident & 128;
  67. if(!bAllocated)
  68. {
  69. if(iSize == 0 || iSize == size)
  70. {
  71. *(heap + position) = (size & 127) | 128;
  72. memory_allocated += size;
  73. return (heap + position + 1);
  74. }
  75. }
  76. position += iSize + 1;
  77. }
  78.  
  79. printf("Unable to allocate memory, end of heap\n");
  80. mem_error();
  81.  
  82. return 0;
  83. }
  84.  
  85. void *mem_put(void *o, int size)
  86. {
  87. void *mem = mem_alloc(size);
  88. memcpy(mem,o,size);
  89. return mem;
  90. }
  91.  
  92. void mem_free(void *mem)
  93. {
  94. int addr = mem - (void *) heap;
  95. char ident = (char) *(heap + addr - 1);
  96. char iSize = ident & 127;
  97. char bAllocated = ident & 128;
  98. if(!bAllocated) return;
  99.  
  100. printf("%i SIZE\n",iSize);
  101.  
  102. memory_allocated -= iSize;
  103. *(heap + addr - 1) = ident & 127;
  104. }
  105.  
  106. void mem_destroy()
  107. {
  108. free(heap);
  109. }
  110.  
  111. int total_allocated()
  112. {
  113. return memory_allocated;
  114. }
Add Comment
Please, Sign In to add comment