# alloc_func.hpp

Go to the documentation of this file.

    00001 /* $Id: alloc_func.hpp 15291 2009-01-29 02:42:36Z Yexo $ */
    00002
    00005 #ifndef ALLOC_FUNC_HPP
    00006 #define ALLOC_FUNC_HPP
    00007
    00014 void NORETURN MallocError(size_t size);
    00015 void NORETURN ReallocError(size_t size);
    00016
    00027 template <typename T>
    00028 static FORCEINLINE T *MallocT(size_t num_elements)
    00029 {
    00030   /*
    00031    * MorphOS cannot handle 0 elements allocations, or rather that always
    00032    * returns NULL. So we do that for *all* allocations, thus causing it
    00033    * to behave the same on all OSes.
    00034    */
    00035   if (num_elements == 0) return NULL;
    00036
    00037   T *t_ptr = (T*)malloc(num_elements * sizeof(T));
    00038   if (t_ptr == NULL) MallocError(num_elements * sizeof(T));
    00039   return t_ptr;
    00040 }
    00041
    00052 template <typename T>
    00053 static FORCEINLINE T *CallocT(size_t num_elements)
    00054 {
    00055   /*
    00056    * MorphOS cannot handle 0 elements allocations, or rather that always
    00057    * returns NULL. So we do that for *all* allocations, thus causing it
    00058    * to behave the same on all OSes.
    00059    */
    00060   if (num_elements == 0) return NULL;
    00061
    00062   T *t_ptr = (T*)calloc(num_elements, sizeof(T));
    00063   if (t_ptr == NULL) MallocError(num_elements * sizeof(T));
    00064   return t_ptr;
    00065 }
    00066
    00078 template <typename T>
    00079 static FORCEINLINE T *ReallocT(T *t_ptr, size_t num_elements)
    00080 {
    00081   /*
    00082    * MorphOS cannot handle 0 elements allocations, or rather that always
    00083    * returns NULL. So we do that for *all* allocations, thus causing it
    00084    * to behave the same on all OSes.
    00085    */
    00086   if (num_elements == 0) {
    00087     free(t_ptr);
    00088     return NULL;
    00089   }
    00090
    00091   t_ptr = (T*)realloc(t_ptr, num_elements * sizeof(T));
    00092   if (t_ptr == NULL) ReallocError(num_elements * sizeof(T));
    00093   return t_ptr;
    00094 }
    00095
    00097 #define AllocaM(T, num_elements) ((T*)alloca((num_elements) * sizeof(T)))
    00098
    00099 #endif /* ALLOC_FUNC_HPP */