12 #ifndef ALLOC_FUNC_HPP 13 #define ALLOC_FUNC_HPP 33 if (num_elements > SIZE_MAX / element_size)
MallocError(SIZE_MAX);
59 static inline T *
MallocT(
size_t num_elements)
66 if (num_elements == 0)
return NULL;
69 CheckAllocationConstraints<T>(num_elements);
71 T *t_ptr = (T*)malloc(num_elements *
sizeof(T));
72 if (t_ptr == NULL)
MallocError(num_elements *
sizeof(T));
87 static inline T *
CallocT(
size_t num_elements)
94 if (num_elements == 0)
return NULL;
96 T *t_ptr = (T*)calloc(num_elements,
sizeof(T));
97 if (t_ptr == NULL)
MallocError(num_elements *
sizeof(T));
112 template <
typename T>
113 static inline T *
ReallocT(T *t_ptr,
size_t num_elements)
120 if (num_elements == 0) {
126 CheckAllocationConstraints<T>(num_elements);
128 t_ptr = (T*)realloc(t_ptr, num_elements *
sizeof(T));
129 if (t_ptr == NULL)
ReallocError(num_elements *
sizeof(T));
134 #define AllocaM(T, num_elements) \ 135 (CheckAllocationConstraints<T>(num_elements), \ 136 (T*)alloca((num_elements) * sizeof(T))) static T * MallocT(size_t num_elements)
Simplified allocation function that allocates the specified number of elements of the given type...
static T * ReallocT(T *t_ptr, size_t num_elements)
Simplified reallocation function that allocates the specified number of elements of the given type...
static T * CallocT(size_t num_elements)
Simplified allocation function that allocates the specified number of elements of the given type...
void NORETURN MallocError(size_t size)
Function to exit with an error message after malloc() or calloc() have failed.
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
void NORETURN ReallocError(size_t size)
Function to exit with an error message after realloc() have failed.
static void CheckAllocationConstraints(size_t element_size, size_t num_elements)
Checks whether allocating memory would overflow size_t.