lmem.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. ** $Id: lmem.c,v 1.54 2002/05/01 20:40:42 roberto Exp roberto $
  3. ** Interface to Memory Manager
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdlib.h>
  7. #include "lua.h"
  8. #include "ldebug.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. #define MINSIZEARRAY 4
  18. void *luaM_growaux (lua_State *L, void *block, int *size, int size_elems,
  19. int limit, const char *errormsg) {
  20. void *newblock;
  21. int newsize = (*size)*2;
  22. if (newsize < MINSIZEARRAY)
  23. newsize = MINSIZEARRAY; /* minimum size */
  24. else if (*size >= limit/2) { /* cannot double it? */
  25. if (*size < limit - MINSIZEARRAY) /* try something smaller... */
  26. newsize = limit; /* still have at least MINSIZEARRAY free places */
  27. else luaG_runerror(L, errormsg);
  28. }
  29. newblock = luaM_realloc(L, block,
  30. cast(lu_mem, *size)*cast(lu_mem, size_elems),
  31. cast(lu_mem, newsize)*cast(lu_mem, size_elems));
  32. *size = newsize; /* update only when everything else is OK */
  33. return newblock;
  34. }
  35. /*
  36. ** generic allocation routine.
  37. */
  38. void *luaM_realloc (lua_State *L, void *block, lu_mem oldsize, lu_mem size) {
  39. if (size == 0) {
  40. l_free(block, oldsize); /* block may be NULL; that is OK for free */
  41. block = NULL;
  42. }
  43. else if (size >= MAX_SIZET)
  44. luaG_runerror(L, "memory allocation error: block too big");
  45. else {
  46. block = l_realloc(block, oldsize, size);
  47. if (block == NULL) {
  48. if (L)
  49. luaD_error(L, MEMERRMSG, LUA_ERRMEM);
  50. else return NULL; /* error before creating state! */
  51. }
  52. }
  53. if (L && G(L)) {
  54. G(L)->nblocks -= oldsize;
  55. G(L)->nblocks += size;
  56. }
  57. return block;
  58. }