lmem.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. ** $Id: lmem.c,v 1.70.1.1 2007/12/27 13:02:25 roberto Exp $
  3. ** Interface to Memory Manager
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lmem_c
  7. #define LUA_CORE
  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 * frealloc (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. ** * frealloc(ud, NULL, 0, x) creates a new block of size `x'
  22. **
  23. ** * frealloc(ud, p, x, 0) frees the block `p'
  24. ** (in this specific case, frealloc must return NULL).
  25. ** particularly, frealloc(ud, NULL, 0, 0) does nothing
  26. ** (which is equivalent to free(NULL) in ANSI C)
  27. **
  28. ** frealloc 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, size_t 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) /* cannot grow even a little? */
  38. luaG_runerror(L, errormsg);
  39. newsize = limit; /* still have at least one free place */
  40. }
  41. else {
  42. newsize = (*size)*2;
  43. if (newsize < MINSIZEARRAY)
  44. newsize = MINSIZEARRAY; /* minimum size */
  45. }
  46. newblock = luaM_reallocv(L, block, *size, newsize, size_elems);
  47. *size = newsize; /* update only when everything else is OK */
  48. return newblock;
  49. }
  50. void *luaM_toobig (lua_State *L) {
  51. luaG_runerror(L, "memory allocation error: block too big");
  52. return NULL; /* to avoid warnings */
  53. }
  54. /*
  55. ** generic allocation routine.
  56. */
  57. void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
  58. global_State *g = G(L);
  59. lua_assert((osize == 0) == (block == NULL));
  60. block = (*g->frealloc)(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->totalbytes = (g->totalbytes - osize) + nsize;
  65. return block;
  66. }