xref: /netbsd-src/external/gpl2/libmalloc/dist/memalign.c (revision 478e07dd80b73ca7b8dd26ada880f65ffb83aad5)
1 /*	$NetBSD: memalign.c,v 1.1.1.1 2016/01/13 21:42:18 christos Exp $	*/
2 
3 /* Copyright (C) 1991, 1992, 1993, 1994, 1995 Free Software Foundation, Inc.
4 
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
9 
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 Library General Public License for more details.
14 
15 You should have received a copy of the GNU Library General Public
16 License along with this library; see the file COPYING.LIB.  If
17 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
18 Cambridge, MA 02139, USA.  */
19 
20 #ifndef	_MALLOC_INTERNAL
21 #define _MALLOC_INTERNAL
22 #include <malloc.h>
23 #endif
24 
25 __ptr_t (*__memalign_hook) __P ((size_t __size, size_t __alignment));
26 
27 __ptr_t
memalign(alignment,size)28 memalign (alignment, size)
29      __malloc_size_t alignment;
30      __malloc_size_t size;
31 {
32   __ptr_t result;
33   unsigned long int adj;
34 
35   if (__memalign_hook)
36     return (*__memalign_hook) (alignment, size);
37 
38   size = ((size + alignment - 1) / alignment) * alignment;
39 
40   result = malloc (size);
41   if (result == NULL)
42     return NULL;
43   adj = (unsigned long int) ((unsigned long int) ((char *) result -
44 						  (char *) NULL)) % alignment;
45   if (adj != 0)
46     {
47       struct alignlist *l;
48       for (l = _aligned_blocks; l != NULL; l = l->next)
49 	if (l->aligned == NULL)
50 	  /* This slot is free.  Use it.  */
51 	  break;
52       if (l == NULL)
53 	{
54 	  l = (struct alignlist *) malloc (sizeof (struct alignlist));
55 	  if (l == NULL)
56 	    {
57 	      free (result);
58 	      return NULL;
59 	    }
60 	  l->next = _aligned_blocks;
61 	  _aligned_blocks = l;
62 	}
63       l->exact = result;
64       result = l->aligned = (char *) result + alignment - adj;
65     }
66 
67   return result;
68 }
69