Programming Tips - C/C++: strlcat Concatenate two strings ensuring no buffer overflows and a terminating NUL

Date: 2007oct16 Update: 2026sep14 Language: C/C++ Keywords: LPCSTR, LPSTR, LPTSTR, LPCTSTR Q. C/C++: strlcat Concatenate two strings ensuring no buffer overflows and a terminating NUL A. This function does just that:
#include <stddef.h> #include <string.h> #include <stdio.h> 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 = strlen(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; }
Example Use:
void main() { { // With a larger buffer char buf[100] = "hello "; strlcat(buf, "world", sizeof(buf)); printf(" larger buf=%s\n", buf); } { // With a smaller buffer char buf[10] = "hello "; strlcat(buf, "world", sizeof(buf)); printf("smaller buf=%s\n", buf); } }
Outputs:
larger buf=hello world smaller buf=hello wor