From 435f587ed05e2c4d542e1db9ae9e4efbb7e02305 Mon Sep 17 00:00:00 2001 From: Roberto Ierusalimschy Date: Fri, 4 Aug 2000 16:38:35 -0300 Subject: (much) better handling of memory alloction errors --- lstate.c | 39 ++++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) (limited to 'lstate.c') diff --git a/lstate.c b/lstate.c index 34c86bb1..2d7de542 100644 --- a/lstate.c +++ b/lstate.c @@ -1,5 +1,5 @@ /* -** $Id: lstate.c,v 1.28 2000/06/30 14:35:17 roberto Exp roberto $ +** $Id: lstate.c,v 1.29 2000/06/30 19:17:08 roberto Exp roberto $ ** Global State ** See Copyright Notice in lua.h */ @@ -28,8 +28,14 @@ lua_State *lua_state = NULL; lua_State *lua_newstate (int stacksize, int put_builtin) { + struct lua_longjmp myErrorJmp; lua_State *L = luaM_new(NULL, lua_State); - L->errorJmp = NULL; + if (L == NULL) return NULL; /* memory allocation error */ + L->stack = NULL; + L->strt.size = L->udt.size = 0; + L->strt.nuse = L->udt.nuse = 0; + L->strt.hash = NULL; + L->udt.hash = NULL; L->Mbuffer = NULL; L->Mbuffbase = 0; L->Mbuffsize = 0; @@ -40,6 +46,7 @@ lua_State *lua_newstate (int stacksize, int put_builtin) { L->rootcl = NULL; L->roottable = NULL; L->IMtable = NULL; + L->last_tag = -1; L->refArray = NULL; L->refSize = 0; L->refFree = NONEXT; @@ -49,16 +56,23 @@ lua_State *lua_newstate (int stacksize, int put_builtin) { L->callhook = NULL; L->linehook = NULL; L->allowhooks = 1; - L->gt = luaH_new(L, 10); - if (stacksize == 0) stacksize = DEFAULT_STACK_SIZE; - luaD_init(L, stacksize); - luaS_init(L); - luaX_init(L); - luaT_init(L); - if (put_builtin) - luaB_predefine(L); - L->GCthreshold = L->nblocks*4; - return L; + L->errorJmp = &myErrorJmp; + if (setjmp(myErrorJmp.b) == 0) { /* to catch memory allocation errors */ + L->gt = luaH_new(L, 10); + luaD_init(L, (stacksize == 0) ? DEFAULT_STACK_SIZE : stacksize); + luaS_init(L); + luaX_init(L); + luaT_init(L); + if (put_builtin) + luaB_predefine(L); + L->GCthreshold = L->nblocks*4; + L->errorJmp = NULL; + return L; + } + else { /* memory allocation error: free partial state */ + lua_close(L); + return NULL; + } } @@ -75,7 +89,6 @@ void lua_close (lua_State *L) { luaM_free(L, L->Cblocks); LUA_ASSERT(L->numCblocks == 0, "Cblocks still open"); LUA_ASSERT(L->nblocks == 0, "wrong count for nblocks"); - LUA_ASSERT(L->Cstack.base == L->top, "C2Lua not empty"); luaM_free(L, L); if (L == lua_state) { LUA_ASSERT(memdebug_numblocks == 0, "memory leak!"); -- cgit v1.2.3-55-g6feb