2
0

lmem.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. ** $Id: lmem.c,v 1.48 2001/02/23 17:17:25 roberto Exp roberto $
  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, (lu_mem)(*size)*(lu_mem)size_elems,
  29. (lu_mem)newsize*(lu_mem)size_elems);
  30. *size = newsize; /* update only when everything else is OK */
  31. return newblock;
  32. }
  33. /*
  34. ** generic allocation routine.
  35. */
  36. void *luaM_realloc (lua_State *L, void *block, lu_mem oldsize, lu_mem size) {
  37. if (size == 0) {
  38. l_free(block, oldsize); /* block may be NULL; that is OK for free */
  39. block = NULL;
  40. }
  41. else if (size >= MAX_SIZET)
  42. luaD_error(L, l_s("memory allocation error: block too big"));
  43. else {
  44. block = l_realloc(block, oldsize, size);
  45. if (block == NULL) {
  46. if (L)
  47. luaD_breakrun(L, LUA_ERRMEM); /* break run without error message */
  48. else return NULL; /* error before creating state! */
  49. }
  50. }
  51. if (L && G(L)) {
  52. G(L)->nblocks -= oldsize;
  53. G(L)->nblocks += size;
  54. }
  55. return block;
  56. }