Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #ifndef ALLOC_FUNC_HPP
00013 #define ALLOC_FUNC_HPP
00014
00015
00016
00017
00018
00019
00020
00021
00022 void NORETURN MallocError(size_t size);
00023 void NORETURN ReallocError(size_t size);
00024
00031 static inline void CheckAllocationConstraints(size_t element_size, size_t num_elements)
00032 {
00033 if (num_elements > SIZE_MAX / element_size) MallocError(SIZE_MAX);
00034 }
00035
00042 template <typename T>
00043 static inline void CheckAllocationConstraints(size_t num_elements)
00044 {
00045 CheckAllocationConstraints(sizeof(T), num_elements);
00046 }
00047
00058 template <typename T>
00059 static FORCEINLINE T *MallocT(size_t num_elements)
00060 {
00061
00062
00063
00064
00065
00066 if (num_elements == 0) return NULL;
00067
00068
00069 CheckAllocationConstraints<T>(num_elements);
00070
00071 T *t_ptr = (T*)malloc(num_elements * sizeof(T));
00072 if (t_ptr == NULL) MallocError(num_elements * sizeof(T));
00073 return t_ptr;
00074 }
00075
00086 template <typename T>
00087 static FORCEINLINE T *CallocT(size_t num_elements)
00088 {
00089
00090
00091
00092
00093
00094 if (num_elements == 0) return NULL;
00095
00096 T *t_ptr = (T*)calloc(num_elements, sizeof(T));
00097 if (t_ptr == NULL) MallocError(num_elements * sizeof(T));
00098 return t_ptr;
00099 }
00100
00112 template <typename T>
00113 static FORCEINLINE T *ReallocT(T *t_ptr, size_t num_elements)
00114 {
00115
00116
00117
00118
00119
00120 if (num_elements == 0) {
00121 free(t_ptr);
00122 return NULL;
00123 }
00124
00125
00126 CheckAllocationConstraints<T>(num_elements);
00127
00128 t_ptr = (T*)realloc(t_ptr, num_elements * sizeof(T));
00129 if (t_ptr == NULL) ReallocError(num_elements * sizeof(T));
00130 return t_ptr;
00131 }
00132
00134 #define AllocaM(T, num_elements) \
00135 (CheckAllocationConstraints<T>(num_elements), \
00136 (T*)alloca((num_elements) * sizeof(T)))
00137
00138 #endif