14 #ifndef STXXL_COMMON_ALIGNED_ALLOC_HEADER
15 #define STXXL_COMMON_ALIGNED_ALLOC_HEADER
22 #ifndef STXXL_VERBOSE_ALIGNED_ALLOC
23 #define STXXL_VERBOSE_ALIGNED_ALLOC STXXL_VERBOSE2
28 template <
typename MustBeInt>
33 template <
typename MustBeInt>
47 template <
size_t Alignment>
50 STXXL_VERBOSE2(
"stxxl::aligned_alloc<" << Alignment <<
">(), size = " << size <<
", meta info size = " << meta_info_size);
51 #if !defined(STXXL_WASTE_MORE_MEMORY_FOR_IMPROVED_ACCESS_AFTER_ALLOCATED_MEMORY_CHECKS)
57 size_t alloc_size = Alignment +
sizeof(
char*) + meta_info_size + size;
68 size_t alloc_size = Alignment *
div_ceil(
sizeof(
char*) + meta_info_size, Alignment) + size;
70 if (posix_memalign((
void**)&buffer, Alignment, alloc_size) != 0)
71 throw std::bad_alloc();
74 throw std::bad_alloc();
75 #ifdef STXXL_ALIGNED_CALLOC
76 memset(buffer, 0, alloc_size);
78 char* reserve_buffer = buffer +
sizeof(
char*) + meta_info_size;
79 char* result = reserve_buffer + Alignment -
80 (((
unsigned_type)reserve_buffer) % (Alignment)) - meta_info_size;
81 STXXL_VERBOSE2(
"stxxl::aligned_alloc<" << Alignment <<
">() address " << (
void*)result <<
" lost " << (result - buffer) <<
" bytes");
85 assert(
long(result - buffer) >=
long(
sizeof(
char*)));
89 size_t realloc_size = (result - buffer) + meta_info_size + size;
91 char* realloced = (
char*)
std::realloc(buffer, realloc_size);
92 if (buffer != realloced) {
95 STXXL_ERRMSG(
"stxxl::aligned_alloc: disabling realloc()");
98 return aligned_alloc<Alignment>(size, meta_info_size);
100 assert(result + size <= buffer + realloc_size);
103 *(((
char**)result) - 1) = buffer;
105 "stxxl::aligned_alloc<" << Alignment <<
">(), allocated at " <<
106 (
void*)buffer <<
" returning " << (
void*)result);
108 "stxxl::aligned_alloc<" << Alignment <<
109 ">(size = " << size <<
", meta info size = " << meta_info_size <<
110 ") => buffer = " << (
void*)buffer <<
", ptr = " << (
void*)result);
115 template <
size_t Alignment>
121 char* buffer = *(((
char**)ptr) - 1);
128 #endif // !STXXL_COMMON_ALIGNED_ALLOC_HEADER
void * malloc(size_t size)
compat::remove_const< Integral >::type div_ceil(Integral n, Integral2 d)
static bool may_use_realloc
void * realloc(void *ptr, size_t size)
#define STXXL_VERBOSE2(x)
#define STXXL_VERBOSE_ALIGNED_ALLOC
#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)
void aligned_dealloc(void *ptr)
#define STXXL_END_NAMESPACE