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

Using `strncat` for safer concatenation

Using strncat for safer concatenation

What you'll learn: How to prevent memory corruption by limiting the number of characters added to a string during concatenation.

The Overflow Problem

Imagine you have a small physical folder that can only hold 10 sheets of paper. If you try to force 20 sheets into it, the folder rips, and papers spill onto your desk, covering up other important documents.

In C, the standard strcat function acts like someone who ignores the size of your "folder" (the destination array). It blindly appends the source string to the end of the destination. If the resulting combined string is larger than the memory you allocated, it spills over, overwriting neighboring data. This is a buffer overflow, a major source of crashes and security vulnerabilities.

Meet strncat

The strncat function is the "safety-first" version of concatenation. The "n" stands for a specific number of characters. It requires a third argument: the maximum number of characters to append. By calculating how much space is left in your array, you ensure the string never "rips" its container.

How to use it

To use strncat safely, you must tell it exactly how many slots are remaining in your array, minus one (to leave room for the invisible \0 null terminator that marks the end of a string).

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

int main() {
    char greeting[15] = "Hello, ";
    char name[] = "Programmer!";
    
    // We have 15 total slots. 
    // "Hello, " uses 7 slots. 
    // Remaining space: 15 - 7 = 8.
    // We should copy at most 7 characters to leave room for '\0'.
    
    strncat(greeting, name, 7); 
    
    printf("%s\n", greeting); // Output: Hello, Program
    return 0;
}

In the example above, strncat stops after 7 characters. Even though name is longer, the program remains stable because we didn't exceed the 15-byte limit of the greeting array.

Best Practices

Always calculate your limit as sizeof(destination) - strlen(destination) - 1. This ensures that no matter how long the source string is, it will always fit perfectly within the boundaries you defined, keeping your program's memory tidy and secure.

Key takeaway

Use strncat instead of strcat to define a hard limit on how many characters are added, preventing dangerous buffer overflows.