Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 15 Jul 1999 23:20:04 -0400
From:      Bakul Shah <bakul@torrentnet.com>
To:        freebsd-hackers@FreeBSD.ORG
Subject:   Re: OpenBSD's strlcpy(3) and strlcat(3) 
Message-ID:  <199907160320.XAA03039@chai.torrentnet.com>

next in thread | raw e-mail | index | archive | help
Any use of str{,n}cat makes me gag.  In the past I have used
a composable function that may be of interest.  Composable in
the sense that the result can be immediately used as an arg
to another call and it doesn't have the O(N^2) behavior of
strcat.  Such a function can be totally safe.  Something like:

	char* r;
	r = scpy(char* dst, char* const dst_end, const char* src)

where the following post-conditions hold:

	dst_end >= dst
	r == MIN(dst + strlen(src)), dst_end)
	r[0] == '\0'

That is, the returned ptr points in `dst' _just_ past the
copied data.  Note that `dst_end' points to the _last_ char
of `dst'.

Example:

	char* string[N];
	    ...
	char str[STRSIZE];
	char* const strend = str + sizeof str - 1;
	char* t = str;

	for (int i = 0; i < N && t < strend; i++)
		t = scpy(t, strend, string[i]);

or
	scpy(scpy(str, strend, "this"), strend, " and that"));


Here is the implementation:

char*
scpy(char* d, char* const e, const char* s)
{
	while (*s && d < e)
		*d++ = *s++;
	*d = '\0';
	return d;
}

This is far too simple to merit a paper or a long name :-)
And I am sure a zillion others have come up with the same idea.

-- bakul


To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?199907160320.XAA03039>