lmem.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. ** $Id: lmem.c,v 1.62 2003/10/02 20:31:17 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;
  36. if (*size >= limit/2) { /* cannot double it? */
  37. if (*size >= limit - MINSIZEARRAY) /* try something smaller... */
  38. luaG_runerror(L, errormsg);
  39. newsize = limit; /* still have at least MINSIZEARRAY free places */
  40. }
  41. else {
  42. newsize = (*size)*2;
  43. if (newsize < MINSIZEARRAY)
  44. newsize = MINSIZEARRAY; /* minimum size */
  45. }
  46. newblock = luaM_realloc(L, block,
  47. cast(lu_mem, *size)*cast(lu_mem, size_elems),
  48. cast(lu_mem, newsize)*cast(lu_mem, size_elems));
  49. *size = newsize; /* update only when everything else is OK */
  50. return newblock;
  51. }
  52. /*
  53. ** generic allocation routine.
  54. */
  55. void *luaM_realloc (lua_State *L, void *block, lu_mem osize, lu_mem nsize) {
  56. global_State *g = G(L);
  57. lua_assert((osize == 0) == (block == NULL));
  58. if (nsize >= MAX_SIZET)
  59. luaG_runerror(L, "memory allocation error: block too big");
  60. block = (*g->realloc)(g->ud, block, osize, nsize);
  61. if (block == NULL && nsize > 0)
  62. luaD_throw(L, LUA_ERRMEM);
  63. lua_assert((nsize == 0) == (block == NULL));
  64. g->nblocks -= osize;
  65. g->nblocks += nsize;
  66. return block;
  67. }