lua-users home
lua-l archive

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


On Sat, Apr 17, 2010 at 11:25 AM, Sean Conner <sean@conman.org> wrote:
> static int strhex(lua_State *L)
> {
>  const char *s;
>  size_t      size;
>  size_t      max;
>  char       *ns;
>  char       *p;
>
>  s  = luaL_checklstring(L,1,&size);
>  ns = malloc((size * 2) + 1);
>
>  for ( p = ns , max = size ; max > 0 ; max--)
>  {
>    sprintf(p,"%02X",*s++);
>    p += 2;
>  }
>
>  lua_pushlstring(L,ns,size * 2);
>  free(ns);
>  return 1;
> }
Of course, this will cause a memory leak if the call to
lua_pushlstring throws a (memory) error. Hence why I would use "ns =
lua_newuserdata(L, (size * 2) + 1)" instead of malloc, as then Lua is
guaranteed to free this temporary buffer, even if something goes awry.