mem.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. {
  23. #if 0
  24. if (ptr)
  25. #endif
  26. free(ptr);
  27. }
  28. /** Portable implementation of malloc() function.
  29. *
  30. * The faux library implements its own free() function (called faux_free()) so
  31. * it's suitable to implement their own complementary malloc() function.
  32. * The behaviour when the size is 0 must be strictly defined. This function
  33. * will assert() and return NULL when size is 0.
  34. *
  35. * @param [in] size Memory size to allocate.
  36. * @return Allocated memory or NULL on error.
  37. * @sa malloc()
  38. */
  39. void *faux_malloc(size_t size)
  40. {
  41. assert(size != 0);
  42. if (0 == size)
  43. return NULL;
  44. return malloc(size);
  45. }
  46. /** Portable implementation of bzero().
  47. *
  48. * The POSIX standard says the bzero() is legacy now. It recommends to use
  49. * memset() instead it. But bzero() is easier to use. So bzero() can be
  50. * implemented using memset().
  51. *
  52. * @param [in] ptr Pointer
  53. * @param [in] size Size of memory (in bytes) to zero it.
  54. * @sa bzero()
  55. */
  56. void faux_bzero(void *ptr, size_t size)
  57. {
  58. memset(ptr, '\0', size);
  59. }
  60. /** The malloc() implementation with writing zeroes to allocated buffer.
  61. *
  62. * The POSIX defines calloc() function to allocate memory and write zero bytes
  63. * to the whole buffer. But calloc() has strange set of arguments. This function
  64. * is simply combination of malloc() and bzero().
  65. *
  66. * @param [in] size Memory size to allocate.
  67. * @return Allocated zeroed memory or NULL on error.
  68. */
  69. void *faux_zmalloc(size_t size)
  70. {
  71. void *ptr = NULL;
  72. ptr = faux_malloc(size);
  73. if (ptr)
  74. faux_bzero(ptr, size);
  75. return ptr;
  76. }