/*1** $Id: lmem.c,v 1.70.1.1 2007/12/27 13:02:25 roberto Exp $2** Interface to Memory Manager3** See Copyright Notice in lua.h4*/567#include <stddef.h>89#define lmem_c10#define LUA_CORE1112#include "lua.h"1314#include "ldebug.h"15#include "ldo.h"16#include "lmem.h"17#include "lobject.h"18#include "lstate.h"19202122/*23** About the realloc function:24** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);25** (`osize' is the old size, `nsize' is the new size)26**27** Lua ensures that (ptr == NULL) iff (osize == 0).28**29** * frealloc(ud, NULL, 0, x) creates a new block of size `x'30**31** * frealloc(ud, p, x, 0) frees the block `p'32** (in this specific case, frealloc must return NULL).33** particularly, frealloc(ud, NULL, 0, 0) does nothing34** (which is equivalent to free(NULL) in ANSI C)35**36** frealloc returns NULL if it cannot create or reallocate the area37** (any reallocation to an equal or smaller size cannot fail!)38*/39404142#define MINSIZEARRAY 4434445void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems,46int limit, const char *errormsg) {47void *newblock;48int newsize;49if (*size >= limit/2) { /* cannot double it? */50if (*size >= limit) /* cannot grow even a little? */51luaG_runerror(L, errormsg);52newsize = limit; /* still have at least one free place */53}54else {55newsize = (*size)*2;56if (newsize < MINSIZEARRAY)57newsize = MINSIZEARRAY; /* minimum size */58}59newblock = luaM_reallocv(L, block, *size, newsize, size_elems);60*size = newsize; /* update only when everything else is OK */61return newblock;62}636465void *luaM_toobig (lua_State *L) {66luaG_runerror(L, "memory allocation error: block too big");67return NULL; /* to avoid warnings */68}69707172/*73** generic allocation routine.74*/75void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {76global_State *g = G(L);77lua_assert((osize == 0) == (block == NULL));78block = (*g->frealloc)(g->ud, block, osize, nsize);79if (block == NULL && nsize > 0)80luaD_throw(L, LUA_ERRMEM);81lua_assert((nsize == 0) == (block == NULL));82g->totalbytes = (g->totalbytes - osize) + nsize;83return block;84}85868788