bug in putenv()!

Jonathan Ballard asmodeus at tree.UUCP
Fri Feb 17 13:21:51 AEST 1989


Hi!

For some reason putenv() is not setting the environment variables right
with certain array declarations.  I wrote a putenv() replacement which 
works fine.  So I assume that either putenv() has a bug in it or that 
the format is different then normal in this version of UNIX.  Which is it?
I'm using System V/AT 2.4.

Here are some examples of what went wrong.

In this example, putenv will return ok but it never sets $USERNAME.
>	char envbuf[100];
>
>	sprintf(envbuf,"USERNAME=%s","hi");
>	putenv(envbuf);

But it works right if done like this...
>	putenv("USERNAME=hi");

The strange part is it works with numbers when doing a sprintf...
>	sprintf(envbuf,"USERNUM=%d",13);
>	putenv(envbuf);

I made my own putenv() routine (called "PutEnv()") that does what putenv()
is susposed to do and it works fine.  If you need to use this then
go ahead and modify it in any way.  I'm not responsible for any damage
done if you do use this.  I have no way of throughly testing it against
everything that putenv() does so this shouldn't be used as total replacement
of putenv(), unless someone can say it does the full job.

-----------------------------------8<----------------------------------------

PutEnv(str)
char *str;
{
	
	int i,len;
	extern char **environ;
	char **tmpenvp,*envp;  /* this is used just in case malloc or realloc
				fails and the orginal pointer value could
				be saved */

	len=strcspn(str,"=");
	/* check first to see if there is an environment, 
		if not then make one */
	if(environ==(char **)0) {
		if((environ=(char **)malloc(sizeof(char *)))==(char **)0)
			return(-1);
		environ[0]=(char *)0;
	}

	/* now check to see if the enviromental varible is already there
		if it is then replace the value with the new one */
	for(i=0;environ[i]!=(char *)0;i++) 
		if(strncmp(str,environ[i],len+1)==0) {
			envp=environ[i];
			if((environ[i]=(char *)realloc(environ[i],strlen(str)+1))==(char *)0) {
				environ[i]=envp;
				return(-1);
			}
			strcpy(environ[i],str);
			return(0);
		}
	tmpenvp=environ;
	/* if there isn't a matching environmental varible then create it */
	if((environ=(char **)realloc(environ,(i+2)*sizeof(char *)))==(char **)0)
	{
		environ=tmpenvp;
		return(-1);
	}
	if((environ[i]=(char *)malloc(strlen(str)+1))==(char *)0)
		return(-1);
	environ[i+1]=(char *)0;
	strcpy(environ[i],str);
	return(0);
}
-- 
----Asmodeus - Jonathan Ballard  ..!csusac!tree!asmodeus
				 ..!pacbell!sactoh0!tree!asmodeus
"I'm going to create the best game ever heard of!
	Might take a few years thou..." -me



More information about the Comp.unix.wizards mailing list