lmem.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. ** $Id: lmem.c,v 1.47 2001/02/20 18:15:33 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 "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. void *luaM_growaux (lua_State *L, void *block, int *size, int size_elems,
  17. int limit, const l_char *errormsg) {
  18. void *newblock;
  19. int newsize = (*size)*2;
  20. if (newsize < MINPOWER2)
  21. newsize = MINPOWER2; /* minimum size */
  22. else if (*size >= limit/2) { /* cannot double it? */
  23. if (*size < limit - MINPOWER2) /* try something smaller... */
  24. newsize = limit; /* still have at least MINPOWER2 free places */
  25. else luaD_error(L, errormsg);
  26. }
  27. newblock = luaM_realloc(L, block, (lu_mem)(*size)*(lu_mem)size_elems,
  28. (lu_mem)newsize*(lu_mem)size_elems);
  29. *size = newsize; /* update only when everything else is OK */
  30. return newblock;
  31. }
  32. /*
  33. ** generic allocation routine.
  34. */
  35. void *luaM_realloc (lua_State *L, void *block, lu_mem oldsize, lu_mem size) {
  36. if (size == 0) {
  37. l_free(block, oldsize); /* block may be NULL; that is OK for free */
  38. block = NULL;
  39. }
  40. else if (size >= MAX_SIZET)
  41. luaD_error(L, l_s("memory allocation error: block too big"));
  42. else {
  43. block = l_realloc(block, oldsize, size);
  44. if (block == NULL) {
  45. if (L)
  46. luaD_breakrun(L, LUA_ERRMEM); /* break run without error message */
  47. else return NULL; /* error before creating state! */
  48. }
  49. }
  50. if (L && G(L)) {
  51. G(L)->nblocks -= oldsize;
  52. G(L)->nblocks += size;
  53. }
  54. return block;
  55. }