Dave's Brain

Browse - Programming Tips - Is there a C/C++ function to concatenate two strings ensuring

Date: 2007oct16
Language: C/C++
Keywords: LPCSTR, LPSTR, LPTSTR, LPCTSTR

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; }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.