Fix a typo in the changelog
[openal-soft.git] / common / almalloc.cpp
blob4d7ff62c896e838446a502ec494e929323c25247
2 #include "config.h"
4 #include "almalloc.h"
6 #include <cassert>
7 #include <cstddef>
8 #include <cstdlib>
9 #include <cstring>
10 #include <memory>
11 #ifdef HAVE_MALLOC_H
12 #include <malloc.h>
13 #endif
16 void *al_malloc(size_t alignment, size_t size)
18 assert((alignment & (alignment-1)) == 0);
19 alignment = std::max(alignment, alignof(std::max_align_t));
21 #if defined(HAVE_STD_ALIGNED_ALLOC)
22 size = (size+(alignment-1))&~(alignment-1);
23 return std::aligned_alloc(alignment, size);
24 #elif defined(HAVE_POSIX_MEMALIGN)
25 void *ret{};
26 if(posix_memalign(&ret, alignment, size) == 0)
27 return ret;
28 return nullptr;
29 #elif defined(HAVE__ALIGNED_MALLOC)
30 return _aligned_malloc(size, alignment);
31 #else
32 size_t total_size{size + alignment-1 + sizeof(void*)};
33 void *base{std::malloc(total_size)};
34 if(base != nullptr)
36 void *aligned_ptr{static_cast<char*>(base) + sizeof(void*)};
37 total_size -= sizeof(void*);
39 std::align(alignment, size, aligned_ptr, total_size);
40 *(static_cast<void**>(aligned_ptr)-1) = base;
41 base = aligned_ptr;
43 return base;
44 #endif
47 void *al_calloc(size_t alignment, size_t size)
49 void *ret{al_malloc(alignment, size)};
50 if(ret) std::memset(ret, 0, size);
51 return ret;
54 void al_free(void *ptr) noexcept
56 #if defined(HAVE_STD_ALIGNED_ALLOC) || defined(HAVE_POSIX_MEMALIGN)
57 std::free(ptr);
58 #elif defined(HAVE__ALIGNED_MALLOC)
59 _aligned_free(ptr);
60 #else
61 if(ptr != nullptr)
62 std::free(*(static_cast<void**>(ptr) - 1));
63 #endif