[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Portability issue with `putenv'
From: |
James Youngman |
Subject: |
Re: Portability issue with `putenv' |
Date: |
Mon, 21 Feb 2005 19:24:40 +0000 |
User-agent: |
Mutt/1.3.28i |
On Mon, Feb 21, 2005 at 07:23:20PM +0100, Sam Lauber wrote:
>
> >
> > > 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".
James.