base.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /** @file base.c
  2. * @brief Base faux functions.
  3. */
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <assert.h>
  7. #include "faux/faux.h"
  8. /** Portable implementation of free() function.
  9. *
  10. * The POSIX standard says the free() must check pointer for NULL value
  11. * and must not try to free NULL pointer. I.e. it do nothing in a case of NULL.
  12. * The Linux glibc do so. But some non-fully POSIX compatible systems don't.
  13. * For these systems our implementation of free() must check for NULL itself.
  14. *
  15. * For now function simply call free() but it can be changed while working on
  16. * portability.
  17. *
  18. * @param [in] ptr Memory pointer to free.
  19. * @sa free()
  20. */
  21. void faux_free(void *ptr) {
  22. #if 0
  23. if (ptr)
  24. #endif
  25. free(ptr);
  26. }
  27. /** Portable implementation of malloc() function.
  28. *
  29. * The faux library implements its own free() function (called faux_free()) so
  30. * it's suitable to implement their own complementary malloc() function.
  31. * The behaviour when the size is 0 must be strictly defined. This function
  32. * will assert() and return NULL when size is 0.
  33. *
  34. * @param [in] size Memory size to allocate.
  35. * @return Allocated memory or NULL on error.
  36. * @sa malloc()
  37. */
  38. void *faux_malloc(size_t size) {
  39. assert(size != 0);
  40. if (0 == size)
  41. return NULL;
  42. return malloc(size);
  43. }
  44. /** Portable implementation of bzero().
  45. *
  46. * The POSIX standard says the bzero() is legacy now. It recommends to use
  47. * memset() instead it. But bzero() is easier to use. So bzero() can be
  48. * implemented using memset().
  49. *
  50. * @param [in] ptr Pointer
  51. * @param [in] size Size of memory (in bytes) to zero it.
  52. * @sa bzero()
  53. */
  54. void faux_bzero(void *ptr, size_t size) {
  55. memset(ptr, '\0', size);
  56. }
  57. /** The malloc() implementation with writing zeroes to allocated buffer.
  58. *
  59. * The POSIX defines calloc() function to allocate memory and write zero bytes
  60. * to the whole buffer. But calloc() has strange set of arguments. This function
  61. * is simply combination of malloc() and bzero().
  62. *
  63. * @param [in] size Memory size to allocate.
  64. * @return Allocated zeroed memory or NULL on error.
  65. */
  66. void *faux_zmalloc(size_t size) {
  67. void *ptr = NULL;
  68. ptr = faux_malloc(size);
  69. if (ptr)
  70. faux_bzero(ptr, size);
  71. return ptr;
  72. }