1 /* 2 Copyright 2014-2015 Glen Joseph Fernandes 3 (glenjofe@gmail.com) 4 5 Distributed under the Boost Software License, Version 1.0. 6 (http://www.boost.org/LICENSE_1_0.txt) 7 */ 8 #ifndef BOOST_ALIGN_DETAIL_ALIGNED_ALLOC_HPP 9 #define BOOST_ALIGN_DETAIL_ALIGNED_ALLOC_HPP 10 11 #include <boost/align/detail/is_alignment.hpp> 12 #include <boost/align/align.hpp> 13 #include <boost/align/alignment_of.hpp> 14 #include <boost/assert.hpp> 15 #include <cstdlib> 16 17 namespace boost { 18 namespace alignment { 19 20 inline void* aligned_alloc(std::size_t alignment,std::size_t size)21aligned_alloc(std::size_t alignment, std::size_t size) BOOST_NOEXCEPT 22 { 23 BOOST_ASSERT(detail::is_alignment(alignment)); 24 enum { 25 N = alignment_of<void*>::value 26 }; 27 if (alignment < N) { 28 alignment = N; 29 } 30 std::size_t n = size + alignment - N; 31 void* p = std::malloc(sizeof(void*) + n); 32 if (p) { 33 void* r = static_cast<char*>(p) + sizeof(void*); 34 (void)boost::alignment::align(alignment, size, r, n); 35 *(static_cast<void**>(r) - 1) = p; 36 p = r; 37 } 38 return p; 39 } 40 41 inline void aligned_free(void * ptr)42aligned_free(void* ptr) BOOST_NOEXCEPT 43 { 44 if (ptr) { 45 std::free(*(static_cast<void**>(ptr) - 1)); 46 } 47 } 48 49 } /* alignment */ 50 } /* boost */ 51 52 #endif 53