1 /* -*- mode: c; tab-width: 4; fill-column: 128 -*- */
2 /* vi: set ts=4 tw=128: */
5 aligned_malloc.c, Copyright (c) 2014 Dave Odell <dmo2118@gmail.com>
7 Permission to use, copy, modify, distribute, and sell this software and its
8 documentation for any purpose is hereby granted without fee, provided that
9 the above copyright notice appear in all copies and that both that
10 copyright notice and this permission notice appear in supporting
11 documentation. No representations are made about the suitability of this
12 software for any purpose. It is provided "as is" without express or
16 #include "aligned_malloc.h"
24 /* aligned_alloc() (C11) or posix_memalign() (POSIX) are other possibilities
28 int aligned_malloc(void **ptr, unsigned alignment, size_t size)
31 ptrdiff_t align1 = alignment - 1;
33 assert(alignment && !(alignment & (alignment - 1))); /* alignment must be a power of two. */
35 size += sizeof(void *) + align1;
36 block_start = malloc(size);
39 *ptr = (void *)(((ptrdiff_t)block_start + sizeof(void *) + align1) & ~align1);
40 ((void **)(*ptr))[-1] = block_start;
44 void aligned_free(void *ptr)
47 free(((void **)(ptr))[-1]);