lmem.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. ** $Id: lmem.c,v 1.60 2002/11/21 14:14:42 roberto Exp roberto $
  3. ** Interface to Memory Manager
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdlib.h>
  7. #define lmem_c
  8. #include "lua.h"
  9. #include "ldebug.h"
  10. #include "ldo.h"
  11. #include "lmem.h"
  12. #include "lobject.h"
  13. #include "lstate.h"
  14. /*
  15. ** definition for realloc function. It must assure that l_realloc(NULL,
  16. ** 0, x) allocates a new block (ANSI C assures that). (`os' is the old
  17. ** block size; some allocators may use that.)
  18. */
  19. #ifndef l_realloc
  20. #define l_realloc(b,os,s) realloc(b,s)
  21. #endif
  22. /*
  23. ** definition for free function. (`os' is the old block size; some
  24. ** allocators may use that.)
  25. */
  26. #ifndef l_free
  27. #define l_free(b,os) free(b)
  28. #endif
  29. #define MINSIZEARRAY 4
  30. void *luaM_growaux (lua_State *L, void *block, int *size, int size_elems,
  31. int limit, const char *errormsg) {
  32. void *newblock;
  33. int newsize = (*size)*2;
  34. if (newsize < MINSIZEARRAY)
  35. newsize = MINSIZEARRAY; /* minimum size */
  36. else if (*size >= limit/2) { /* cannot double it? */
  37. if (*size < limit - MINSIZEARRAY) /* try something smaller... */
  38. newsize = limit; /* still have at least MINSIZEARRAY free places */
  39. else luaG_runerror(L, errormsg);
  40. }
  41. newblock = luaM_realloc(L, block,
  42. cast(lu_mem, *size)*cast(lu_mem, size_elems),
  43. cast(lu_mem, newsize)*cast(lu_mem, size_elems));
  44. *size = newsize; /* update only when everything else is OK */
  45. return newblock;
  46. }
  47. /*
  48. ** generic allocation routine.
  49. */
  50. void *luaM_realloc (lua_State *L, void *block, lu_mem oldsize, lu_mem size) {
  51. lua_assert((oldsize == 0) == (block == NULL));
  52. if (size == 0) {
  53. if (block != NULL) {
  54. l_free(block, oldsize);
  55. block = NULL;
  56. }
  57. else return NULL; /* avoid `nblocks' computations when oldsize==size==0 */
  58. }
  59. else if (size >= MAX_SIZET)
  60. luaG_runerror(L, "memory allocation error: block too big");
  61. else {
  62. block = l_realloc(block, oldsize, size);
  63. if (block == NULL) {
  64. if (L)
  65. luaD_throw(L, LUA_ERRMEM);
  66. else return NULL; /* error before creating state! */
  67. }
  68. }
  69. if (L) {
  70. lua_assert(G(L) != NULL && G(L)->nblocks > 0);
  71. G(L)->nblocks -= oldsize;
  72. G(L)->nblocks += size;
  73. }
  74. return block;
  75. }