The ups and downs of strlcpy()
Posted Jul 26, 2012 1:28 UTC (Thu) by
nybble41 (subscriber, #55106)
In reply to:
The ups and downs of strlcpy() by smurf
Parent article:
The ups and downs of strlcpy()
Here's a suggestion (only partly sarcastic):
typedef size_t (*strxcpy_handler_t)(char *dst, const char *src, size_t size, void *data);
size_t strxcpy(char *dst, const char *src, size_t size, strxcpy_handler_t overflow_fn, void *overflow_data)
{
char *p;
const char *q;
for (p = dst, q = src; *q; ++p, ++q)
{
if ((p - dst) >= size)
{
return overflow_fn(dst, src, size, overflow_data);
}
*p = *q;
}
/* get here only if strlen(src) < size */
*p++ = '\0';
return (p - dst);
}
size_t strxcpy_truncate(char *dst, const char *src, size_t size, void *data)
{
if (size <= 0) abort();
dst[size - 1] = '\0';
return size + strlen(src + size);
}
size_t strxcpy_abort(char *dst, const char *src, size_t size, void *data)
{
abort();
return size;
}
if (strxcpy(dst, src, dst_size, strxcpy_truncate, NULL) >= dst_size) ...;
(void)strxcpy(dst, src, dst_size, strxcpy_abort, NULL);
(void)strxcpy(dst, src, dst_size, strxcpy_subst, "(input too long)");
/* ... */
(
Log in to post comments)