A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
strcat appends the source string to the end of the destination buffer. It assumes the destination has enough room. It does not check. If you are wrong about the room, you overflow the buffer. strncat takes a maximum number of characters to append, which bounds the write, but the API is still awkward: the count is characters to copy, not the total buffer size. Getting this wrong is so common that modern code should prefer snprintf for string concatenation.
#include <stdio.h>#include <string.h>int main(void) {char buffer[32] = "Hello";strcat(buffer, ", ");strcat(buffer, "world");strcat(buffer, "!");printf("Result: \"%s\"\n", buffer);printf("Length: %zu\n", strlen(buffer));return 0;}
#include <stdio.h>#include <string.h>int main(void) {char buffer[16] = "Start";size_t remaining = sizeof(buffer) - strlen(buffer) - 1;strncat(buffer, " this is a very long string", remaining);printf("Result: \"%s\"\n", buffer);printf("Length: %zu\n", strlen(buffer));return 0;}
The remaining calculation is sizeof(buffer) - strlen(buffer) - 1. The -1 reserves space for the null terminator that strncat always appends. The third argument to strncat is the maximum number of characters to copy from the source, not including the null. If you pass sizeof(buffer) directly, you overflow by one byte because strncat adds a null after copying. This off-by-one is the classic strncat bug.
#include <stdio.h>#include <string.h>int main(void) {char buffer[32];int written = snprintf(buffer, sizeof(buffer), "%s, %s!", "Hello", "world");if (written < 0 || (size_t)written >= sizeof(buffer)) {printf("Output was truncated.\n");}printf("Result: \"%s\"\n", buffer);return 0;}
snprintf takes the total buffer size. It handles the null terminator. It reports truncation via the return value. It formats and concatenates in one call. For new code, prefer snprintf over strcat and strncat. The older functions exist for historical reasons and for codebases that predate C99. In greenfield code, snprintf is safer and more readable.
String concatenation in C is a buffer management exercise. Every append is a potential overflow if you miscalculate the remaining space. snprintf eliminates most of that risk. Use it. Next: handling string input with spaces, where scanf fails and fgets takes over.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.