lmem.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. ** $Id: lmem.c,v 1.63 2003/11/27 18:18:37 roberto Exp roberto $
  3. ** Interface to Memory Manager
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stddef.h>
  7. #define lmem_c
  8. #define LUA_CORE
  9. #include "lua.h"
  10. #include "ldebug.h"
  11. #include "ldo.h"
  12. #include "lmem.h"
  13. #include "lobject.h"
  14. #include "lstate.h"
  15. /*
  16. ** About the realloc function:
  17. ** void * realloc (void *ud, void *ptr, size_t osize, size_t nsize);
  18. ** (`osize' is the old size, `nsize' is the new size)
  19. **
  20. ** Lua ensures that (ptr == NULL) iff (osize == 0).
  21. **
  22. ** * realloc(ud, NULL, 0, x) creates a new block of size `x'
  23. **
  24. ** * realloc(ud, p, x, 0) frees the block `p'
  25. ** (in this specific case, realloc must return NULL).
  26. ** particularly, realloc(ud, NULL, 0, 0) does nothing
  27. ** (which is equivalent to free(NULL) in ANSI C)
  28. **
  29. ** realloc returns NULL if it cannot create or reallocate the area
  30. ** (any reallocation to an equal or smaller size cannot fail!)
  31. */
  32. #define MINSIZEARRAY 4
  33. void *luaM_growaux (lua_State *L, void *block, int *size, int size_elems,
  34. int limit, const char *errormsg) {
  35. void *newblock;
  36. int newsize;
  37. if (*size >= limit/2) { /* cannot double it? */
  38. if (*size >= limit - MINSIZEARRAY) /* try something smaller... */
  39. luaG_runerror(L, errormsg);
  40. newsize = limit; /* still have at least MINSIZEARRAY free places */
  41. }
  42. else {
  43. newsize = (*size)*2;
  44. if (newsize < MINSIZEARRAY)
  45. newsize = MINSIZEARRAY; /* minimum size */
  46. }
  47. newblock = luaM_realloc(L, block,
  48. cast(lu_mem, *size)*cast(lu_mem, size_elems),
  49. cast(lu_mem, newsize)*cast(lu_mem, size_elems));
  50. *size = newsize; /* update only when everything else is OK */
  51. return newblock;
  52. }
  53. /*
  54. ** generic allocation routine.
  55. */
  56. void *luaM_realloc (lua_State *L, void *block, lu_mem osize, lu_mem nsize) {
  57. global_State *g = G(L);
  58. lua_assert((osize == 0) == (block == NULL));
  59. if (nsize >= MAX_SIZET)
  60. luaG_runerror(L, "memory allocation error: block too big");
  61. block = (*g->realloc)(g->ud, block, osize, nsize);
  62. if (block == NULL && nsize > 0)
  63. luaD_throw(L, LUA_ERRMEM);
  64. lua_assert((nsize == 0) == (block == NULL));
  65. g->nblocks -= osize;
  66. g->nblocks += nsize;
  67. return block;
  68. }