lmem.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. #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 * frealloc (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. ** * frealloc(ud, NULL, 0, x) creates a new block of size `x'
  23. **
  24. ** * frealloc(ud, p, x, 0) frees the block `p'
  25. ** (in this specific case, frealloc must return NULL).
  26. ** particularly, frealloc(ud, NULL, 0, 0) does nothing
  27. ** (which is equivalent to free(NULL) in ANSI C)
  28. **
  29. ** frealloc 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, size_t size_elems,
  34. int limit, const char *errormsg)
  35. {
  36. void *newblock;
  37. int newsize;
  38. if (*size >= limit / 2) /* cannot double it? */
  39. {
  40. if (*size >= limit) /* cannot grow even a little? */
  41. luaG_runerror(L, errormsg);
  42. newsize = limit; /* still have at least one free place */
  43. }
  44. else
  45. {
  46. newsize = (*size) * 2;
  47. if (newsize < MINSIZEARRAY)
  48. newsize = MINSIZEARRAY; /* minimum size */
  49. }
  50. newblock = luaM_reallocv(L, block, *size, newsize, size_elems);
  51. *size = newsize; /* update only when everything else is OK */
  52. return newblock;
  53. }
  54. void *luaM_toobig(lua_State *L)
  55. {
  56. luaG_runerror(L, "memory allocation error: block too big");
  57. return NULL; /* to avoid warnings */
  58. }
  59. /*
  60. ** generic allocation routine.
  61. */
  62. void *luaM_realloc_(lua_State *L, void *block, size_t osize, size_t nsize)
  63. {
  64. global_State *g = G(L);
  65. lua_assert((osize == 0) == (block == NULL));
  66. block = (*g->frealloc)(g->ud, block, osize, nsize);
  67. if (block == NULL && nsize > 0)
  68. luaD_throw(L, LUA_ERRMEM);
  69. lua_assert((nsize == 0) == (block == NULL));
  70. g->totalbytes = (g->totalbytes - osize) + nsize;
  71. return block;
  72. }