1 /*****************************************************************************
2 * posix_memalign.c: POSIX posix_memalign() replacement
3 *****************************************************************************
4 * Copyright © 2012, 2019 Rémi Denis-Courmont
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published by
8 * the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
19 *****************************************************************************/
33 static void *memalign(size_t align
, size_t size
)
35 void *p
= malloc(size
);
37 if ((uintptr_t)p
& (align
- 1)) {
47 static int check_align(size_t align
)
49 if (align
& (align
- 1)) /* must be a power of two */
51 if (align
< sizeof (void *)) /* must be a multiple of sizeof (void *) */
56 int posix_memalign(void **ptr
, size_t align
, size_t size
)
58 int val
= check_align(align
);
62 /* Unlike posix_memalign(), legacy memalign() requires that size be a
65 if (size
> (SIZE_MAX
/ 2))
68 size
+= (-size
) & (align
- 1);
70 int saved_errno
= errno
;
71 void *p
= memalign(align
, size
);