Dave's Brain

Browse - programming tips - strlcat

Date: 2007oct16
Language: C/C++

Q.  Is there a C/C++ function to concatenate two strings ensuring
    no buffer overflows and a terminating NUL?

A.  This function does the trick:

size_t strlcat(char *dst, const char *src, const size_t size)
{
	size_t		len_dst;
	size_t		len_src;
	size_t		len_result;

	if (dst == NULL) return 0;
	len_dst = len_result = strlen(dst);
	if (src == NULL) return len_result;
	len_src = lstrlen(src);
	len_result += len_src;

	if (len_dst + len_src >= size)
	{
		len_src = size - (len_dst + 1);
	}

	if (len_src > 0)
	{
		memcpy(dst + len_dst, src, len_src);
		dst[len_dst + len_src] = '\0';
	}

	return len_result;
}

Keywords: LPCSTR, LPSTR, LPTSTR, LPCTSTR

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.