4 // by David Raingeard (Cal2)
5 // GCC/SDL port by Niels Wagenaar (Linux/WIN32) and Caz (BeOS)
6 // Cleanups by James L. Hammons
14 // Useful structs (for doubly linked list in this case)
16 typedef struct sMemBlockInfo
25 // Private global variables
27 static sMemBlockInfo memoryInfo;
28 //static UINT32 memoryMaxAllocated;
29 static UINT32 currentAllocatedMemory;
30 static UINT32 maximumAllocatedMemory;
33 void memory_addMemInfo(void * ptr, UINT32 size, char * info)
35 sMemBlockInfo * alias = &memoryInfo;
40 alias->next = (sMemBlockInfo *)malloc(sizeof(sMemBlockInfo));
42 if (alias->next == NULL)
48 alias->next->prev = alias;
58 memoryInfo.next = memoryInfo.prev = NULL;
59 currentAllocatedMemory = maximumAllocatedMemory = 0;
66 void * memory_malloc(UINT32 size, char * info)
68 void * ptr = (void *)malloc(size);
73 memory_addMemInfo(ptr, size, info);
74 currentAllocatedMemory += size;
76 if (currentAllocatedMemory > maximumAllocatedMemory)
77 maximumAllocatedMemory = currentAllocatedMemory;
82 void memory_malloc_secure(void ** new_ptr, UINT32 size, char * info)
84 WriteLog("Memory: Allocating %i bytes of memory for <%s>...", size, (info == NULL ? "unknown" : info));
86 void * ptr = malloc(size);
90 WriteLog("Failed!\n");
95 memory_addMemInfo(ptr, size, info);
96 currentAllocatedMemory += size;
98 if (currentAllocatedMemory > maximumAllocatedMemory)
99 maximumAllocatedMemory = currentAllocatedMemory;
105 void memory_free(void * ptr)
107 // sMemBlockInfo * alias= &memoryInfo;
108 // alias = alias->next;
109 sMemBlockInfo * alias= memoryInfo.next;
111 while (alias->ptr != ptr)
114 WriteLog("Memory: Freeing %i bytes from <%s>...\n", (int)alias->size, alias->info);
117 currentAllocatedMemory -= alias->size;
118 alias->prev->next = alias->next;
120 if (alias->next != NULL)
121 alias->next->prev = alias->prev;
126 void memory_memoryUsage(FILE * fp)
130 fprintf(fp, "Memory usage:\n");
132 // sMemBlockInfo * alias = &memoryInfo;
133 // alias = alias->next;
134 sMemBlockInfo * alias= memoryInfo.next;
138 fprintf(fp, "\t%16i bytes: <%s> (@ %08X)\n", (int)alias->size, alias->info, (unsigned int)alias->ptr);
139 total += alias->size;
143 fprintf(fp, "\n\t%16i bytes total(%i Mb)\n", (int)total, (int)(total >> 20));
144 fprintf(fp, "\n\t%16i bytes memory peak(%i Mb)\n", (int)maximumAllocatedMemory, (int)(maximumAllocatedMemory >> 20));