[Dev-luatex] Rationale for using putenv?

David Kastrup dak at gnu.org
Mon Apr 2 10:08:28 CEST 2007


in luastuff.c we have

static int os_setenv (lua_State *L) {
  char *value, *key, *val;
  key =  (char *)luaL_optstring(L, 1, NULL);
  val =  (char *)luaL_optstring(L, 2, NULL);
  if (key) {
	if (val) {
	  value = xmalloc(strlen(key)+strlen(val)+2);
	  if (putenv(value)) {
		return luaL_error(L, "unable to change environment");
	} else {
#if defined(WIN32) || defined(__sun__)
	  value = xmalloc(strlen(key)+2);
	  if (putenv(value)) {
		return luaL_error(L, "unable to change environment");
  lua_pushboolean (L, 1);
  return 1;

Now putenv is not required by Posix, as opposed to setenv.  The main
rationale for "putenv" is that it leaves memory management of the
string to the application, and thus can avoid leaking memory.
However, the above code just uses xmalloc without deallocating
previously set values, so it leaks, anyway.

Basically I see two ways of dealing with this:

a) maintain a table of key -> "key=value" mappings for environment
   variables that have been set by Lua.  That way, one can keep track
   of what strings need to stay allocated, and which can be
   deallocated again.
b) don't bother about the leak and use setenv instead.

Option b) would be somewhat more portable, I believe.  Of course, if
people actually use os_setenv to switch around between environment
variables frequently, the leak might get annoying at some point of

David Kastrup

More information about the dev-luatex mailing list