xalloc-oversized.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. /* xalloc-oversized.h -- memory allocation size checking
  2. Copyright (C) 1990-2000, 2003-2004, 2006-2013 Free Software Foundation, Inc.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. #ifndef XALLOC_OVERSIZED_H_
  14. # define XALLOC_OVERSIZED_H_
  15. # include <stddef.h>
  16. /* Return 1 if an array of N objects, each of size S, cannot exist due
  17. to size arithmetic overflow. S must be positive and N must be
  18. nonnegative. This is a macro, not a function, so that it
  19. works correctly even when SIZE_MAX < N.
  20. By gnulib convention, SIZE_MAX represents overflow in size
  21. calculations, so the conservative dividend to use here is
  22. SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value.
  23. However, malloc (SIZE_MAX) fails on all known hosts where
  24. sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for
  25. exactly-SIZE_MAX allocations on such hosts; this avoids a test and
  26. branch when S is known to be 1. */
  27. # define xalloc_oversized(n, s) \
  28. ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n))
  29. #endif /* !XALLOC_OVERSIZED_H_ */