Course contentsShow
← C
Lesson 435 of 1,2196. Arrays and StringsFree lesson

Using `strncpy` for safer copying

Using strncpy for safer copying

What you'll learn: How to prevent memory overflows by limiting the number of characters copied into a string.

The danger of the open gate

In C, the standard strcpy function is like a gardener who keeps planting flowers until they run out of seeds, even if they’ve wandered out of your yard and onto the highway. It doesn't check if the destination array is large enough to hold the source string. If the source is too long, strcpy will keep writing data into memory it doesn't own, causing a "buffer overflow." This often leads to program crashes or serious security vulnerabilities.

Using the "n" for safety

The strncpy function (the "n" stands for number) adds a crucial safety valve: a limit. You tell the function exactly how many bytes it is allowed to write.

Think of it like a fixed-size shipping box. If you try to shove a giant rug into a small shoebox, strncpy acts as a pair of scissors—it only takes what fits and discards the rest, ensuring your "box" (memory) doesn't burst at the seams.

A practical example

Here is how you use it to protect your destination buffer:

#include <stdio.h>
#include <string.h>

int main() {
    char source[] = "This string is way too long for the buffer!";
    char destination[10];

    // We only copy 9 characters to leave room for the null terminator
    strncpy(destination, source, 9);
    
    // Crucial step: strncpy does NOT add a null terminator if the limit is reached
    destination[9] = '\0';

    printf("Protected string: %s\n", destination); // Outputs: Protected
    return 0;
}

The "Null" catch

There is one important rule to remember: if the source string is longer than the limit you set, strncpy will not add the null terminator (\0) at the end. Without that terminator, other C functions won't know where the string ends and will keep reading into random memory. Always manually set the last character of your destination buffer to \0 after using strncpy to ensure your string is properly closed.

Key takeaway

Use strncpy to specify a maximum copy length and always manually null-terminate the result to prevent memory overflows.