calloc.c 440 B

1234567891011121314151617181920212223
  1. #include <stdlib.h>
  2. #include <errno.h>
  3. #include <string.h>
  4. void *calloc(size_t m, size_t n)
  5. {
  6. void *p;
  7. size_t *z;
  8. if (n && m > (size_t)-1/n) {
  9. errno = ENOMEM;
  10. return 0;
  11. }
  12. n *= m;
  13. p = malloc(n);
  14. if (!p) return 0;
  15. /* Only do this for non-mmapped chunks */
  16. if (((size_t *)p)[-1] & 7) {
  17. /* Only write words that are not already zero */
  18. m = (n + sizeof *z - 1)/sizeof *z;
  19. for (z=p; m; m--, z++) if (*z) *z=0;
  20. }
  21. return p;
  22. }