SHOGUN v0.9.0
|
00001 /* 00002 * This program is free software; you can redistribute it and/or modify 00003 * it under the terms of the GNU General Public License as published by 00004 * the Free Software Foundation; either version 3 of the License, or 00005 * (at your option) any later version. 00006 * 00007 * Written (W) 2008-2009 Soeren Sonnenburg 00008 * Copyright (C) 2008-2009 Fraunhofer Institute FIRST and Max-Planck-Society 00009 */ 00010 00011 #include <stdio.h> 00012 00013 #include "lib/ShogunException.h" 00014 #include "lib/memory.h" 00015 #include "lib/common.h" 00016 #include "lib/Set.h" 00017 00018 using namespace shogun; 00019 00020 #ifdef TRACE_MEMORY_ALLOCS 00021 extern CSet<MemoryBlock>* sg_mallocs; 00022 #endif 00023 00024 void* operator new(size_t size) throw (std::bad_alloc) 00025 { 00026 void *p=malloc(size); 00027 #ifdef TRACE_MEMORY_ALLOCS 00028 if (sg_mallocs) 00029 sg_mallocs->add(MemoryBlock(p,size)); 00030 #endif 00031 if (!p) 00032 { 00033 const size_t buf_len=128; 00034 char buf[buf_len]; 00035 size_t written=snprintf(buf, buf_len, 00036 "Out of memory error, tried to allocate %lld bytes using new().\n", (long long int) size); 00037 if (written<buf_len) 00038 throw ShogunException(buf); 00039 else 00040 throw ShogunException("Out of memory error using new.\n"); 00041 } 00042 00043 return p; 00044 } 00045 00046 void operator delete(void *p) 00047 { 00048 #ifdef TRACE_MEMORY_ALLOCS 00049 if (sg_mallocs) 00050 sg_mallocs->remove(MemoryBlock(p)); 00051 #endif 00052 if (p) 00053 free(p); 00054 } 00055 00056 void* operator new[](size_t size) 00057 { 00058 void *p=malloc(size); 00059 #ifdef TRACE_MEMORY_ALLOCS 00060 if (sg_mallocs) 00061 sg_mallocs->add(MemoryBlock(p,size)); 00062 #endif 00063 00064 if (!p) 00065 { 00066 const size_t buf_len=128; 00067 char buf[buf_len]; 00068 size_t written=snprintf(buf, buf_len, 00069 "Out of memory error, tried to allocate %lld bytes using new[].\n", (long long int) size); 00070 if (written<buf_len) 00071 throw ShogunException(buf); 00072 else 00073 throw ShogunException("Out of memory error using new[].\n"); 00074 } 00075 00076 return p; 00077 } 00078 00079 void operator delete[](void *p) 00080 { 00081 #ifdef TRACE_MEMORY_ALLOCS 00082 if (sg_mallocs) 00083 sg_mallocs->remove(MemoryBlock(p)); 00084 #endif 00085 if (p) 00086 free(p); 00087 } 00088 00089 #ifdef TRACE_MEMORY_ALLOCS 00090 void list_memory_allocs() 00091 { 00092 if (sg_mallocs) 00093 { 00094 int32_t num=sg_mallocs->get_num_elements(); 00095 printf("%d Blocks are allocated:\n", num); 00096 00097 for (int32_t i=0; i<num; i++) 00098 sg_mallocs->get_element(i).display(); 00099 } 00100 } 00101 #endif