lua-users home
lua-l archive

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


On Thu, 24 Mar 2011, Sean Conner wrote:

>     if (argc > 0)
>     {
>       int idx;
>       int i;
>
>       argv = malloc(argc * sizeof(char *));
>       if (argv == NULL)
>         luaL_error(L,"out of memory");
>
>       for (idx = 2 , i = 0 ; i < argc ; i++ , idx++)
>         argv[i] = luaL_checkstring(L,idx);
>     }
>     else
>       argv = NULL;
>   }
>
>   rc = bar(self,argc,argv,&arglen);
>   free(argv);
>   lua_pushinteger(L,rc);
>   return 1;
> }

Its problematic to use malloc()/free() in functions called from Lua
because eg in your routine if luaL_checkstring() fails to find a string
the function will longjmp back to the Lua caller, causing a memory leak..

I normally use lua_newuserdata instead of malloc so that Lua can handle
the cleanup..

(this applies to other resource usages too of course)

iain