alloc.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #include <sys/mman.h>
  7. #ifdef L_calloc_dbg
  8. void *calloc_dbg(size_t num, size_t size, char *function, char *file,
  9. int line)
  10. {
  11. void *ptr;
  12. fprintf(stderr, "calloc of %d bytes at %s @%s:%d = ", num * size,
  13. function, file, line);
  14. ptr = calloc(num, size);
  15. fprintf(stderr, "%p\n", ptr);
  16. return ptr;
  17. }
  18. #endif
  19. #ifdef L_malloc_dbg
  20. void *malloc_dbg(size_t len, char *function, char *file, int line)
  21. {
  22. void *result;
  23. fprintf(stderr, "malloc of %d bytes at %s @%s:%d = ", len, function,
  24. file, line);
  25. result = malloc(len);
  26. fprintf(stderr, "%p\n", result);
  27. return result;
  28. }
  29. #endif
  30. #ifdef L_free_dbg
  31. void free_dbg(void *ptr, char *function, char *file, int line)
  32. {
  33. fprintf(stderr, "free of %p at %s @%s:%d\n", ptr, function, file,
  34. line);
  35. free(ptr);
  36. }
  37. #endif
  38. #ifdef L_calloc
  39. void *calloc(size_t num, size_t size)
  40. {
  41. void *ptr = malloc(num * size);
  42. if (ptr)
  43. memset(ptr, 0, num * size);
  44. return ptr;
  45. }
  46. #endif
  47. #ifdef L_malloc
  48. void *malloc(size_t len)
  49. {
  50. void *result = mmap((void *) 0, len, PROT_READ | PROT_WRITE,
  51. #ifdef __HAS_NO_MMU__
  52. MAP_SHARED | MAP_ANONYMOUS, 0, 0
  53. #else
  54. MAP_PRIVATE | MAP_ANONYMOUS, 0, 0
  55. #endif
  56. );
  57. if (result == MAP_FAILED)
  58. return 0;
  59. return result;
  60. }
  61. #endif
  62. #ifdef L_free
  63. void free(void *ptr)
  64. {
  65. munmap(ptr, 0);
  66. }
  67. #endif
  68. #ifdef L_realloc
  69. void *realloc(void *ptr, size_t size)
  70. {
  71. void *newptr = NULL;
  72. if (size > 0) {
  73. newptr = malloc(size);
  74. if (newptr && ptr) {
  75. memcpy(newptr, ptr, size);
  76. free(ptr);
  77. }
  78. }
  79. else
  80. free(ptr);
  81. return newptr;
  82. }
  83. #endif