14 #ifndef STXXL_COMMON_ALIGNED_ALLOC_HEADER
15 #define STXXL_COMMON_ALIGNED_ALLOC_HEADER
23 #ifndef STXXL_VERBOSE_ALIGNED_ALLOC
24 #define STXXL_VERBOSE_ALIGNED_ALLOC STXXL_VERBOSE2
29 template <
typename must_be_
int>
34 template <
typename must_be_
int>
48 template <
size_t ALIGNMENT>
51 STXXL_VERBOSE2(
"stxxl::aligned_alloc<" << ALIGNMENT <<
">(), size = " << size <<
", meta info size = " << meta_info_size);
52 #if !defined(STXXL_WASTE_MORE_MEMORY_FOR_IMPROVED_ACCESS_AFTER_ALLOCATED_MEMORY_CHECKS)
58 size_t alloc_size = ALIGNMENT +
sizeof(
char*) + meta_info_size + size;
59 char* buffer = (
char*)std::malloc(alloc_size);
69 size_t alloc_size = ALIGNMENT *
div_ceil(
sizeof(
char*) + meta_info_size, ALIGNMENT) + size;
71 if (posix_memalign((
void**)&buffer, ALIGNMENT, alloc_size) != 0)
72 throw std::bad_alloc();
75 throw std::bad_alloc();
76 #ifdef STXXL_ALIGNED_CALLOC
77 memset(buffer, 0, alloc_size);
79 char* reserve_buffer = buffer +
sizeof(
char*) + meta_info_size;
80 char* result = reserve_buffer + ALIGNMENT -
81 (((
unsigned_type)reserve_buffer) % (ALIGNMENT)) - meta_info_size;
82 STXXL_VERBOSE2(
"stxxl::aligned_alloc<" << ALIGNMENT <<
">() address " << (
void*)result <<
" lost " << (result - buffer) <<
" bytes");
86 assert(
long(result - buffer) >=
long(
sizeof(
char*)));
90 size_t realloc_size = (result - buffer) + meta_info_size + size;
92 char* realloced = (
char*)std::realloc(buffer, realloc_size);
93 if (buffer != realloced) {
96 STXXL_ERRMSG(
"stxxl::aligned_alloc: disabling realloc()");
99 return aligned_alloc<ALIGNMENT>(size, meta_info_size);
101 assert(result + size <= buffer + realloc_size);
104 *(((
char**)result) - 1) = buffer;
105 STXXL_VERBOSE2(
"stxxl::aligned_alloc<" << ALIGNMENT <<
">(), allocated at " << (
void*)buffer <<
" returning " << (
void*)result);
107 ">(size = " << size <<
", meta info size = " << meta_info_size <<
108 ") => buffer = " << (
void*)buffer <<
", ptr = " << (
void*)result);
113 template <
size_t ALIGNMENT>
119 char* buffer = *(((
char**)ptr) - 1);
126 #endif // !STXXL_COMMON_ALIGNED_ALLOC_HEADER
#define STXXL_VERBOSE2(x)
#define STXXL_VERBOSE_ALIGNED_ALLOC
static bool may_use_realloc
#define STXXL_BEGIN_NAMESPACE
choose_int_types< my_pointer_size >::unsigned_type unsigned_type
void * aligned_alloc(size_t size, size_t meta_info_size=0)
compat::remove_const< Integral >::type div_ceil(Integral __n, Integral2 __d)
void aligned_dealloc(void *ptr)
#define STXXL_END_NAMESPACE