00001
00002
00009
00010
00011 #include "memory.h"
00012 #include <limits.h>
00013 #include <stdio.h>
00014
00015 void **memlist=0;
00016 unsigned int count=0;
00017 unsigned int sz=0;
00018
00019
00025
00026 void addToList(void *ptr){
00027 if(sz<(count+1)){
00028 if(sz>(UINT_MAX-100)){
00029 printf("Woops: Overflow in memory.c sz\n");
00030 }
00031 sz += 100;
00032 memlist = (void**)realloc((void*)memlist, sz * sizeof(void*));
00033 }
00034 if(!memlist) return;
00035 memlist[count] = ptr;
00036 if(count==UINT_MAX){
00037 printf("Woops: Overflow in memory.c count\n");
00038 }
00039 count++;
00040 }
00041
00042
00051
00052 int removeFromList(void *ptr){
00053 unsigned int i=0;
00054 int found=0;
00055
00056 if(!memlist) return 0;
00057 for(i=0;i<count;i++){
00058 if(memlist[i]==ptr){
00059 found=1;
00060 break;
00061 }
00062 }
00063 if(!found) return 0;
00064 count--;
00065 if(i<count){
00066 memlist[i] = memlist[count];
00067 }
00068 return 1;
00069 }
00070
00071
00074
00075 void *calloc_safe(size_t nmemb, size_t size){
00076 void *temp;
00077 if(!nmemb || !size){
00078 printf("ERR: Calloc called with zero something. Nmemb=%x Size=%x.\n",nmemb, size);
00079 return (void*)0;
00080 }
00081 temp = calloc(nmemb, size);
00082 if(!temp){
00083 printf("WARN: Calloc returned null\n");
00084 }
00085 else addToList(temp);
00086 return temp;
00087 }
00088
00089
00092
00093 void *malloc_safe(size_t size){
00094 void *temp;
00095 if(!size){
00096 printf("ERR: Calloc called with zero size\n");
00097 return (void*)0;
00098 }
00099 temp = malloc(size);
00100 if(!temp){
00101 printf("WARN: Malloc returned null\n");
00102 }
00103 else addToList(temp);
00104 return temp;
00105 }
00106
00107
00110
00111 void free_safe(void *ptr){
00112 if(removeFromList(ptr)) free(ptr);
00113 }
00114
00115
00118
00119 void *realloc_safe(void *ptr, size_t size){
00120 void *temp;
00121 if(!size){
00122 printf("ERR: Realloc called with zero something. ptr=%p Size=%x.\n",ptr, size);
00123 return (void*)0;
00124 }
00125 if(ptr && !removeFromList(ptr)){
00126 printf("ERR: Realloc tried to realloc a non-malloc sourced pointer(%p)\n",ptr);
00127 return (void*)0;
00128 }
00129
00130 temp = (void*)realloc((void*)ptr, size);
00131 if(!temp){
00132 printf("WARN: Realloc returned null\n");
00133 }
00134 else addToList(temp);
00135 return temp;
00136 }
00137
00138
00141
00142 char *strdup_safe(const char *s){
00143 char *temp;
00144 if(!s){
00145 printf("ERR: Strdup called with null string\n");
00146 return (void*)0;
00147 }
00148 temp = strdup(s);
00149 if(!temp){
00150 printf("WARN: Strdup returned null\n");
00151 }
00152 else addToList(temp);
00153 return temp;
00154 }
00155
00156
00160
00161 int cleanup_memory(void){
00162 unsigned int i;
00163
00164 for(i=0;i<count;i++){
00165 if(memlist[i]) free(memlist[i]);
00166 else { printf("WARN: There was a null in memlist, count %u\n", i); }
00167 }
00168
00169 return count;
00170 }