lmem.c 2.2 KB

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