Concatenating strings with strncat
What you'll learn: How to safely glue one string onto the end of another without overflowing your memory buffers.
The "Appended String" Concept
In C, strings don't automatically grow when you add text to them. Think of a string like a physical shelf. If you have a shelf built for five books and you try to cram a sixth one in, you'll break something. Concatenation is the process of taking a "destination" string and appending a "source" string to its end.
The standard library provides strcat, but it is dangerous because it doesn't check if the destination has enough room. Instead, we use strncat, which includes a "safety limit."
How strncat Works
The function takes three arguments: the destination, the source, and the maximum number of characters to copy.
Imagine you have a name tag that can hold 20 characters. You’ve already written "Hi, " (4 characters including the space and null terminator). You want to add a long name like "Constantinople," but you only have a few spots left. strncat lets you say, "Add this name, but stop after N characters so we don't write on the table."
#include <stdio.h>
#include <string.h>
int main() {
char greeting[20] = "Hello, ";
char name[] = "Programmer!";
// We want to add 'name' to 'greeting'.
// We calculate remaining space: 20 total - 7 used - 1 for null = 12.
// To be safe, let's just add 10 characters.
strncat(greeting, name, 10);
printf("%s", greeting); // Outputs: Hello, Programmer
return 0;
}
The Vital Safety Rule
strncat will automatically add a null terminator (\0) at the end of the new string, which is very helpful. However, you must ensure your destination array is large enough to hold the original text, the new text, and that final null terminator.
If your destination array is size 10 and currently holds "Hi" (2 chars + null), you have room for 7 more characters. If you try to strncat 8 characters, you will experience a "buffer overflow," which is a common way programs crash or get hacked. Always do the math before you glue!
Key takeaway
Use strncat to append strings safely by specifying a maximum character limit to avoid overflowing your destination buffer.