tech-pkg archive

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

Re: Theo chiming in on strlcpy



* Marc Espie <espie%nerim.net@localhost> [2013-12-22 00:54]:
> On Sat, Dec 21, 2013 at 03:43:20PM -0800, John Nemeth wrote:
> >      All my code either verify that it will fit the destination
> > string before hand, or use strn* and deals properly with potential
> > truncation.  Overruning a string isn't the only thing that causes
> > security problems.  Truncation is quite capable of doing it as
> > well.  At the very least, the app won't behave properly.  Once you
> > acknowlege this, strl* buys you nothing over strn* or just plain
> > str* with length calculation done before hand.
> 
> Okay, show me your code.

    static char *
    concat(const char *s1, const char *s2)
    {
        size_t l1 = strlen(s1);
        size_t l2 = strlen(s2);
        size_t size;

        if (((size = l1 + l2) <= l1 && l2 != 0) || ++size == 0)
            abort(); /* Handle `size_t' overflow. */
        return strcat(strcpy(xmalloc(size), s1), s2);
    }

(Yes, with pre-calculated lengths, you could use memcpy(3) instead of
the str* functions, trading readability a bit.  And yes, depending on
context, you want to use a variant that allows for limiting the size.)

Actually, the strl* functions can be used to implement stuff like this
slightly nicer, which is why I like them myself.  The problem is that
they tend to be advocated not as a prettier way to implement sane code,
but as a critical tool for replacing arbitrary str* calls in a
quick'n'dirty manner, which is a rationale that is easy to argue
against.

Holger


Home | Main Index | Thread Index | Old Index