From: Keith M. <kei...@to...> - 2007-02-23 16:38:16
|
Daniel K. O. wrote: > Even though the mysetenv() code seems to > leak memory, that's necessary for putenv() - it doesn't copy the > argument, it just points to it; so if you change (or free) the > string after the putenv() call, you may mess with the environment. `seems' is very much the operative word here, for the mysetenv example does *not* leak memory, *if* the putenv call is successful. Yes, the pointer to the string eventually passed to putenv is not directly exposed beyond the scope of mysetenv; it is a local pointer to a malloc'ed buffer, so the buffer continues to exist after mysetenv returns, but the pointer is lost; however, it may be retrieved subsequently, by calling getenv. BTW, I didn't write that sample function; it is exactly as it was in the man-1.5m sources I ported, and may very well be John Eaton's original code. I guess it could be made more robust by free'ing the buffer before returning, if the putenv call fails: static void mysetenv(const char *name, const char *value) { #ifdef HAVE_SETENV setenv(name, value, 1); #else int len = strlen(value)+1+strlen(value)+1; char *str = my_malloc(len); sprintf(str, "%s=%s", name, value); if(putenv(str) != EXIT_SUCCESS) free(str); #endif } (The my_malloc function is a wrapper around malloc; it aborts the program, with an `Out of memory' message, if malloc itself fails). Regards, Keith. |