Stxxl  1.2.1
aligned_alloc.h
1 /***************************************************************************
2  * include/stxxl/bits/common/aligned_alloc.h
3  *
4  * Part of the STXXL. See http://stxxl.sourceforge.net
5  *
6  * Copyright (C) 2002 Roman Dementiev <dementiev@mpi-sb.mpg.de>
7  *
8  * Distributed under the Boost Software License, Version 1.0.
9  * (See accompanying file LICENSE_1_0.txt or copy at
10  * http://www.boost.org/LICENSE_1_0.txt)
11  **************************************************************************/
12 
13 #ifndef STXXL_ALIGNED_ALLOC
14 #define STXXL_ALIGNED_ALLOC
15 
16 #include <stxxl/bits/common/utils.h>
17 
18 
19 __STXXL_BEGIN_NAMESPACE
20 
21 template <size_t ALIGNMENT>
22 inline void * aligned_alloc(size_t size, size_t meta_info_size = 0)
23 {
24  STXXL_VERBOSE1("stxxl::aligned_alloc<" << ALIGNMENT << ">(), size = " << size << ", meta info size = " << meta_info_size);
25  char * buffer = new char[size + ALIGNMENT + sizeof(char *) + meta_info_size];
26  #ifdef STXXL_ALIGNED_CALLOC
27  memset(buffer, 0, size + ALIGNMENT + sizeof(char *) + meta_info_size);
28  #endif
29  char * reserve_buffer = buffer + sizeof(char *) + meta_info_size;
30  char * result = reserve_buffer + ALIGNMENT -
31  (((unsigned long)reserve_buffer) % (ALIGNMENT)) - meta_info_size;
32  STXXL_VERBOSE1("stxxl::aligned_alloc<" << ALIGNMENT << ">() address 0x" << std::hex << long(result)
33  << std::dec << " lost " << unsigned(result - buffer) << " bytes");
34  assert(int(result - buffer) >= int(sizeof(char *)));
35  *(((char **)result) - 1) = buffer;
36  STXXL_VERBOSE1("stxxl::aligned_alloc<" << ALIGNMENT <<
37  ">(), allocated at " << std::hex << ((unsigned long)buffer) << " returning " << ((unsigned long)result)
38  << std::dec);
39 
40  return result;
41 }
42 
43 template <size_t ALIGNMENT>
44 inline void
45 aligned_dealloc(void * ptr)
46 {
47  STXXL_VERBOSE2("stxxl::aligned_dealloc(<" << ALIGNMENT << ">), ptr = 0x" << std::hex << (unsigned long)(ptr) << std::dec);
48  delete[] * (((char **)ptr) - 1);
49 }
50 
51 __STXXL_END_NAMESPACE
52 
53 #endif // !STXXL_ALIGNED_ALLOC