Copying strings safely with strncpy
What you'll learn: How to prevent memory corruption by limiting the number of characters copied between strings.
In C, strings don't have built-in "seatbelts." If you try to pour a gallon of water into a pint-sized glass, the water doesn't just stop; it spills all over your counter. In programming, this is called a buffer overflow. The traditional strcpy function is dangerous because it keeps copying until it hits a null terminator (\0), regardless of whether the destination has enough room.
To stay safe, we use strncpy.
The "Safety Valve" Parameter
Think of strncpy as a version of strcpy that comes with a ruler. You must tell it exactly how many characters it is allowed to copy. It takes three arguments: the destination, the source, and the maximum size.
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "This is a very long sentence.";
char destination[10];
// We only copy 9 characters to leave room for the null terminator
strncpy(destination, source, 9);
// Crucial Step: Manually ensure the string is terminated
destination[9] = '\0';
printf("Result: %s\n", destination); // Output: Result: This is a
return 0;
}
The "Gotcha": The Null Terminator
The strncpy function has a specific quirk you must remember: if the source string is longer than the limit you set, strncpy will fill the destination buffer but will not add the null terminator (\0) at the end.
Without that null terminator, other functions like printf won't know where the string ends. They will keep reading into random parts of your computer's memory, causing crashes or security holes.
As a best practice, always manually set the very last index of your destination array to \0 after using strncpy. This ensures your string is "sealed" properly, no matter what happened during the copy.
When to use it
Use strncpy whenever you are moving data into a fixed-size buffer, especially if that data comes from a user or an external file. It turns a potential system crash into a simple case of "clipping" the text to fit the box.
Key takeaway
Always use strncpy with a size limit and manually null-terminate your destination to prevent dangerous buffer overflows.