alloc.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /*!
  2. \file lib/db/dbmi_base/alloc.c
  3. \brief DBMI Library (base) - allocate memory
  4. (C) 1999-2009, 2011 by the GRASS Development Team
  5. This program is free software under the GNU General Public License
  6. (>=v2). Read the file COPYING that comes with GRASS for details.
  7. \author Joel Jones (CERL/UIUC), Radim Blazek
  8. \author Doxygenized by Martin Landa <landa.martin gmail.com> (2011)
  9. */
  10. #include <string.h>
  11. #include <stdlib.h>
  12. #include <grass/dbmi.h>
  13. /*!
  14. \brief Make a copy of string buffer
  15. Allocated string buffer should be freed by db_free().
  16. \param s source string buffer
  17. \return allocated string buffer
  18. */
  19. char *db_store(const char *s)
  20. {
  21. char *a;
  22. a = db_malloc(strlen(s) + 1);
  23. if (a)
  24. strcpy(a, s);
  25. return a;
  26. }
  27. /*!
  28. \brief Allocate memory
  29. On failure is called db_memory_error().
  30. \param n number of bytes to be allocated
  31. \return pointer to allocated memory
  32. */
  33. void *db_malloc(int n)
  34. {
  35. void *s;
  36. if (n <= 0)
  37. n = 1;
  38. s = malloc((unsigned int)n);
  39. if (s == NULL)
  40. db_memory_error();
  41. return s;
  42. }
  43. /*!
  44. \brief Allocate memory
  45. On failure is called db_memory_error().
  46. \param n number of entities
  47. \param m entity size
  48. \return pointer to allocated memmory
  49. */
  50. void *db_calloc(int n, int m)
  51. {
  52. void *s;
  53. if (n <= 0)
  54. n = 1;
  55. if (m <= 0)
  56. m = 1;
  57. s = calloc((unsigned int)n, (unsigned int)m);
  58. if (s == NULL)
  59. db_memory_error();
  60. return s;
  61. }
  62. /*!
  63. \brief Reallocate memory
  64. On failure is called db_memory_error().
  65. \param s pointer to memory
  66. \param n number of newly allocated bytes
  67. \return pointer to allocated memmory
  68. */
  69. void *db_realloc(void *s, int n)
  70. {
  71. if (n <= 0)
  72. n = 1;
  73. if (s == NULL)
  74. s = malloc((unsigned int)n);
  75. else
  76. s = realloc(s, (unsigned int)n);
  77. if (s == NULL)
  78. db_memory_error();
  79. return s;
  80. }
  81. /*!
  82. \brief Free allocated memory
  83. \param s pointer to memory to be freed
  84. */
  85. void db_free(void *s)
  86. {
  87. free(s);
  88. }