calloc.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. This is a version (aka dlmalloc) of malloc/free/realloc written by
  3. Doug Lea and released to the public domain. Use, modify, and
  4. redistribute this code without permission or acknowledgement in any
  5. way you wish. Send questions, comments, complaints, performance
  6. data, etc to dl@cs.oswego.edu
  7. VERSION 2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee)
  8. Note: There may be an updated version of this malloc obtainable at
  9. ftp://gee.cs.oswego.edu/pub/misc/malloc.c
  10. Check before installing!
  11. Hacked up for uClibc by Erik Andersen <andersen@codepoet.org>
  12. */
  13. #include "malloc.h"
  14. libc_hidden_proto(memset)
  15. /* ------------------------------ calloc ------------------------------ */
  16. void* calloc(size_t n_elements, size_t elem_size)
  17. {
  18. mchunkptr p;
  19. unsigned long clearsize;
  20. unsigned long nclears;
  21. size_t size, *d;
  22. void* mem;
  23. /* guard vs integer overflow, but allow nmemb
  24. * to fall through and call malloc(0) */
  25. size = n_elements * elem_size;
  26. if (n_elements && elem_size != (size / n_elements)) {
  27. __set_errno(ENOMEM);
  28. return NULL;
  29. }
  30. LOCK;
  31. mem = malloc(size);
  32. if (mem != 0) {
  33. p = mem2chunk(mem);
  34. if (!chunk_is_mmapped(p))
  35. {
  36. /*
  37. Unroll clear of <= 36 bytes (72 if 8byte sizes)
  38. We know that contents have an odd number of
  39. size_t-sized words; minimally 3.
  40. */
  41. d = (size_t*)mem;
  42. clearsize = chunksize(p) - (sizeof(size_t));
  43. nclears = clearsize / sizeof(size_t);
  44. assert(nclears >= 3);
  45. if (nclears > 9)
  46. memset(d, 0, clearsize);
  47. else {
  48. *(d+0) = 0;
  49. *(d+1) = 0;
  50. *(d+2) = 0;
  51. if (nclears > 4) {
  52. *(d+3) = 0;
  53. *(d+4) = 0;
  54. if (nclears > 6) {
  55. *(d+5) = 0;
  56. *(d+6) = 0;
  57. if (nclears > 8) {
  58. *(d+7) = 0;
  59. *(d+8) = 0;
  60. }
  61. }
  62. }
  63. }
  64. }
  65. #if 0
  66. else
  67. {
  68. /* Standard unix mmap using /dev/zero clears memory so calloc
  69. * doesn't need to actually zero anything....
  70. */
  71. d = (size_t*)mem;
  72. /* Note the additional (sizeof(size_t)) */
  73. clearsize = chunksize(p) - 2*(sizeof(size_t));
  74. memset(d, 0, clearsize);
  75. }
  76. #endif
  77. }
  78. UNLOCK;
  79. return mem;
  80. }