2
0

lmem.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. ** $Id: lmem.c,v 1.49 2001/03/26 14:31:49 roberto Exp $
  3. ** Interface to Memory Manager
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdlib.h>
  7. #define LUA_PRIVATE
  8. #include "lua.h"
  9. #include "ldo.h"
  10. #include "lmem.h"
  11. #include "lobject.h"
  12. #include "lstate.h"
  13. #ifndef l_realloc
  14. #define l_realloc(b,os,s) realloc(b,s)
  15. #define l_free(b,s) free(b)
  16. #endif
  17. void *luaM_growaux (lua_State *L, void *block, int *size, int size_elems,
  18. int limit, const l_char *errormsg) {
  19. void *newblock;
  20. int newsize = (*size)*2;
  21. if (newsize < MINPOWER2)
  22. newsize = MINPOWER2; /* minimum size */
  23. else if (*size >= limit/2) { /* cannot double it? */
  24. if (*size < limit - MINPOWER2) /* try something smaller... */
  25. newsize = limit; /* still have at least MINPOWER2 free places */
  26. else luaD_error(L, errormsg);
  27. }
  28. newblock = luaM_realloc(L, block,
  29. cast(lu_mem, *size)*cast(lu_mem, size_elems),
  30. cast(lu_mem, newsize)*cast(lu_mem, size_elems));
  31. *size = newsize; /* update only when everything else is OK */
  32. return newblock;
  33. }
  34. /*
  35. ** generic allocation routine.
  36. */
  37. void *luaM_realloc (lua_State *L, void *block, lu_mem oldsize, lu_mem size) {
  38. if (size == 0) {
  39. l_free(block, oldsize); /* block may be NULL; that is OK for free */
  40. block = NULL;
  41. }
  42. else if (size >= MAX_SIZET)
  43. luaD_error(L, l_s("memory allocation error: block too big"));
  44. else {
  45. block = l_realloc(block, oldsize, size);
  46. if (block == NULL) {
  47. if (L)
  48. luaD_breakrun(L, LUA_ERRMEM); /* break run without error message */
  49. else return NULL; /* error before creating state! */
  50. }
  51. }
  52. if (L && G(L)) {
  53. G(L)->nblocks -= oldsize;
  54. G(L)->nblocks += size;
  55. }
  56. return block;
  57. }