memalign.c 1.9 KB

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