[Top][All Lists]

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

Re: Portability issue with `putenv'

From: Sam Lauber
Subject: Re: Portability issue with `putenv'
Date: Tue, 22 Feb 2005 06:27:23 +0100

>>>>> A good replacement for a broken putenv() is (assuming that `putenv'
>>>> is defined as `rpl_putenv'):
>>>> #undef putenv
>>>> int rpl_putenv(s)
>>>>   char *s;
>>>> {
>>>>   char *t;
>>>>   strcpy(t, s);
>>>>   return putenv(t);
>>>> }
>>>> The strcpy() call has an undefined effect as it dereferences an
>>> uninitialised pointer.  Perhaps you meant to put a call to xmalloc()
>>> or strdup() in there.
>>>> If so, what about those callers who already carefully did this: -
>>>>     /* Assume no other thread will modify var or val; also assume
>>>      * we already hold a mutex controlling access to putenv().
>>>      */
>>>     size_t len = strlen(var) + 1u + strlen(val);
>>>     char *s = xmalloc(len + 1u);
>>>     snprintf(s, len+1u, "%s=%s", var, val);
>>>     rpl_putenv(s);
>>>> ... because then you would have a memory leak.
>>> I think I accenditly reversed the argumnts.  In that case, I'll 
>> replace the strcpy() with
>> int n = 0;
>> while (*t++ = *s++)
>>   ++n;
>> while (n-- > 0)
>>   *t--;
>> Samuel Lauber
>> P.S. If you were wondering, the first `while' loop was in Chapter 
>> 5 of `The C Programming Langauge'.  The second `while' was added 
>> to make sure that putenv() would get the address of the beginning 
>> of the string. 
> No, the first while loop is still wrong because "t" is never
> initialised.  Also the second while loop is identical to just "n=0;"
> apart from the fact that it has undefined behaviour because it
> dereferences the uninitialised pointer, "t".

Ok, I give up!  Any way to copy said string is very 
welcome.  If strcpy() does not do it's thing, what will?  

Samuel Lauber
Web-based SMS services available at http://www.operamail.com.
From your mailbox to local or overseas cell phones.

Powered by Outblaze

reply via email to

[Prev in Thread] Current Thread [Next in Thread]