| 1 |
/* |
| 2 |
|
| 3 |
Generic replacement for memalign in terms of xxmalloc and xxfree. |
| 4 |
|
| 5 |
LIMITATIONS: |
| 6 |
|
| 7 |
- This code assumes that the underlying allocator will do "the right |
| 8 |
thing" when xxfree() is called with a pointer internal to an |
| 9 |
allocated object. Header-based allocators, for example, need not |
| 10 |
apply. |
| 11 |
|
| 12 |
*/ |
| 13 |
|
| 14 |
#include <stddef.h> |
| 15 |
|
| 16 |
extern "C" { |
| 17 |
void * xxmalloc(size_t); |
| 18 |
void xxfree(void *); |
| 19 |
} |
| 20 |
|
| 21 |
extern "C" |
| 22 |
void * generic_xxmemalign(size_t alignment, size_t size) { |
| 23 |
// Check for non power-of-two alignment. |
| 24 |
if ((alignment == 0) || (alignment & (alignment - 1))) |
| 25 |
{ |
| 26 |
return nullptr; |
| 27 |
} |
| 28 |
|
| 29 |
if (alignment <= alignof(max_align_t)) { |
| 30 |
// Already aligned by default. |
| 31 |
return xxmalloc(size); |
| 32 |
} else { |
| 33 |
// Try to just allocate an object of the requested size. |
| 34 |
// If it happens to be aligned properly, just return it. |
| 35 |
void * ptr = xxmalloc(size); |
| 36 |
if (((size_t) ptr & ~(alignment - 1)) == (size_t) ptr) { |
| 37 |
// It is already aligned just fine; return it. |
| 38 |
return ptr; |
| 39 |
} |
| 40 |
// It was not aligned as requested: free the object and allocate a big one, |
| 41 |
// and align within. |
| 42 |
xxfree(ptr); |
| 43 |
ptr = xxmalloc (size + 2 * alignment); |
| 44 |
void * alignedPtr = (void *) (((size_t) ptr + alignment - 1) & ~(alignment - 1)); |
| 45 |
return alignedPtr; |
| 46 |
} |
| 47 |
} |