lmem.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. ** $Id: lmem.c,v 1.51 2001/10/25 19:13:33 roberto Exp $
  3. ** Interface to Memory Manager
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdlib.h>
  7. #include "lua.h"
  8. #include "ldo.h"
  9. #include "lmem.h"
  10. #include "lobject.h"
  11. #include "lstate.h"
  12. #ifndef l_realloc
  13. #define l_realloc(b,os,s) realloc(b,s)
  14. #define l_free(b,s) free(b)
  15. #endif
  16. #define MINSIZEARRAY 4
  17. void *luaM_growaux (lua_State *L, void *block, int *size, int size_elems,
  18. int limit, const char *errormsg) {
  19. void *newblock;
  20. int newsize = (*size)*2;
  21. if (newsize < MINSIZEARRAY)
  22. newsize = MINSIZEARRAY; /* minimum size */
  23. else if (*size >= limit/2) { /* cannot double it? */
  24. if (*size < limit - MINSIZEARRAY) /* try something smaller... */
  25. newsize = limit; /* still have at least MINSIZEARRAY 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, "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. }