lmem.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. void *newblock;
  36. int newsize;
  37. if (*size >= limit/2) { /* cannot double it? */
  38. if (*size >= limit) /* cannot grow even a little? */
  39. luaG_runerror(L, errormsg);
  40. newsize = limit; /* still have at least one free place */
  41. }
  42. else {
  43. newsize = (*size)*2;
  44. if (newsize < MINSIZEARRAY)
  45. newsize = MINSIZEARRAY; /* minimum size */
  46. }
  47. newblock = luaM_reallocv(L, block, *size, newsize, size_elems);
  48. *size = newsize; /* update only when everything else is OK */
  49. return newblock;
  50. }
  51. void *luaM_toobig (lua_State *L) {
  52. luaG_runerror(L, "memory allocation error: block too big");
  53. return NULL; /* to avoid warnings */
  54. }
  55. /*
  56. ** generic allocation routine.
  57. */
  58. void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
  59. global_State *g = G(L);
  60. lua_assert((osize == 0) == (block == NULL));
  61. block = (*g->frealloc)(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->totalbytes = (g->totalbytes - osize) + nsize;
  66. return block;
  67. }