[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to pass arguments to argv function effectively in Lua C API
- From: Iain Hibbert <plunky@...>
- Date: Thu, 24 Mar 2011 07:14:50 +0000 (GMT)
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