lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I've managed to reproduce the problem with a minimal test program:

#include <stdio.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

static void* LuaAllocator( void* ud, void* ptr, size_t osize, size_t nsize )
{
  static char core[ 65536 ];
  static int  offset = 0;
  
  void* nptr;
  
  if ( osize == 0 && nsize == 0 )
  {
    /* When nsize is zero, the allocator must return NULL. */
    nptr = 0;
  }
  else if ( osize == 0 && nsize != 0 )
  {
    /* When nsize is not zero and osize is zero, the allocator should behave like malloc. */
    offset = ( offset + 15 ) & ~15;
    nptr = (void*)( core + offset );
    offset += nsize;
  }
  else if ( osize != 0 && nsize == 0 )
  {
    /* If osize is not zero, it should free the block pointed to by ptr. */
    nptr = 0; /* When nsize is zero, the allocator must return NULL. */
  }
  else /* osize != 0 && nsize != 0 */
  {
    /* When nsize and osize are not zero, the allocator behaves like realloc. */
    
    if ( osize < nsize )
    {
      /* Only allocate memory if the new size is greater than the old size. */
      offset = ( offset + 15 ) & ~15;
      nptr = (void*)( core + offset );
      offset += nsize;
    }
    else
    {
      /* Otherwise we recycle the memory. */
      nptr = ptr;
    }
  }
  
  printf( "ptr=%p osize=%4u nsize=%4u nptr=%p used=%.8u\n", ptr, osize, nsize, nptr, offset );
  fflush( stdout );
  return nptr;
}

int main()
{
  lua_State* L = lua_newstate( LuaAllocator, 0 );
  
  if ( L == 0 )
  {
    return 0;
  }
  
  int top = lua_gettop( L );
  luaL_openlibs( L );
  lua_settop( L, top );
  
  lua_pushinteger( L, 0 );
  lua_setglobal( L, "_THREADID" );
  
  luaL_dostring( L, "for i=1,10 do print( i, 'threadid', _THREADID ) end" );
  
  lua_close( L );
  return 0;
}

If I use the default allocator (luaL_newstate) the program runs fine.

Thanks,

Andre Leiradella