memalign.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* Copyright (C) 1991, 1992 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. #include <stdlib.h>
  15. #include "malloc.h"
  16. __ptr_t
  17. memalign (alignment, size)
  18. size_t alignment;
  19. size_t size;
  20. {
  21. __ptr_t result;
  22. unsigned long int adj;
  23. result = malloc (size + alignment - 1);
  24. if (result == NULL)
  25. return NULL;
  26. adj = (unsigned long int) ((unsigned long int) ((char *) result -
  27. (char *) NULL)) % alignment;
  28. if (adj != 0)
  29. {
  30. struct alignlist *l;
  31. for (l = _aligned_blocks; l != NULL; l = l->next)
  32. if (l->aligned == NULL)
  33. /* This slot is free. Use it. */
  34. break;
  35. if (l == NULL)
  36. {
  37. l = (struct alignlist *) malloc (sizeof (struct alignlist));
  38. if (l == NULL)
  39. {
  40. #if 1
  41. free (result);
  42. #else
  43. _free_internal (result);
  44. #endif
  45. return NULL;
  46. }
  47. l->next = _aligned_blocks;
  48. _aligned_blocks = l;
  49. }
  50. l->exact = result;
  51. result = l->aligned = (char *) result + alignment - adj;
  52. }
  53. return result;
  54. }