rlm@1: /* rlm@1: ** $Id: lmem.c,v 1.70.1.1 2007/12/27 13:02:25 roberto Exp $ rlm@1: ** Interface to Memory Manager rlm@1: ** See Copyright Notice in lua.h rlm@1: */ rlm@1: rlm@1: rlm@1: #include rlm@1: rlm@1: #define lmem_c rlm@1: #define LUA_CORE rlm@1: rlm@1: #include "lua.h" rlm@1: rlm@1: #include "ldebug.h" rlm@1: #include "ldo.h" rlm@1: #include "lmem.h" rlm@1: #include "lobject.h" rlm@1: #include "lstate.h" rlm@1: rlm@1: rlm@1: rlm@1: /* rlm@1: ** About the realloc function: rlm@1: ** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize); rlm@1: ** (`osize' is the old size, `nsize' is the new size) rlm@1: ** rlm@1: ** Lua ensures that (ptr == NULL) iff (osize == 0). rlm@1: ** rlm@1: ** * frealloc(ud, NULL, 0, x) creates a new block of size `x' rlm@1: ** rlm@1: ** * frealloc(ud, p, x, 0) frees the block `p' rlm@1: ** (in this specific case, frealloc must return NULL). rlm@1: ** particularly, frealloc(ud, NULL, 0, 0) does nothing rlm@1: ** (which is equivalent to free(NULL) in ANSI C) rlm@1: ** rlm@1: ** frealloc returns NULL if it cannot create or reallocate the area rlm@1: ** (any reallocation to an equal or smaller size cannot fail!) rlm@1: */ rlm@1: rlm@1: rlm@1: rlm@1: #define MINSIZEARRAY 4 rlm@1: rlm@1: rlm@1: void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems, rlm@1: int limit, const char *errormsg) { rlm@1: void *newblock; rlm@1: int newsize; rlm@1: if (*size >= limit/2) { /* cannot double it? */ rlm@1: if (*size >= limit) /* cannot grow even a little? */ rlm@1: luaG_runerror(L, errormsg); rlm@1: newsize = limit; /* still have at least one free place */ rlm@1: } rlm@1: else { rlm@1: newsize = (*size)*2; rlm@1: if (newsize < MINSIZEARRAY) rlm@1: newsize = MINSIZEARRAY; /* minimum size */ rlm@1: } rlm@1: newblock = luaM_reallocv(L, block, *size, newsize, size_elems); rlm@1: *size = newsize; /* update only when everything else is OK */ rlm@1: return newblock; rlm@1: } rlm@1: rlm@1: rlm@1: void *luaM_toobig (lua_State *L) { rlm@1: luaG_runerror(L, "memory allocation error: block too big"); rlm@1: return NULL; /* to avoid warnings */ rlm@1: } rlm@1: rlm@1: rlm@1: rlm@1: /* rlm@1: ** generic allocation routine. rlm@1: */ rlm@1: void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { rlm@1: global_State *g = G(L); rlm@1: lua_assert((osize == 0) == (block == NULL)); rlm@1: block = (*g->frealloc)(g->ud, block, osize, nsize); rlm@1: if (block == NULL && nsize > 0) rlm@1: luaD_throw(L, LUA_ERRMEM); rlm@1: lua_assert((nsize == 0) == (block == NULL)); rlm@1: g->totalbytes = (g->totalbytes - osize) + nsize; rlm@1: return block; rlm@1: } rlm@1: