strlen, strcpy, and strcat in C

In the programming paradigm of C, character arrays (char array) serve as the fundamental structure for storing and processing text data. Since C lacks built-in high-level string object management features like those found in Python or Java, developers must rely on a suite of low-level functions provided by the standard library <string.h> to manipulate sequences of characters within memory. Among these, strlen, strcpy, and strcat are the most commonly used and critical functions, respectively responsible for determining length, copying content, and concatenating content, forming the core foundation of C string processing.
The primary function of strlen() is to return the length of a string that terminates with the null character \0 (ASCII code 0). Note that the "length" calculated here does not include the null character itself. The function performs counting by traversing the array until it encounters the terminator.

In practical development, understanding strlen is crucial for dynamic memory allocation. For instance, if we wish to allocate a buffer of just sufficient size based on the length of user input text, using malloc(strlen(input) + 1) offers greater flexibility than fixed-size static arrays. Here is a simple example:

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

int main() {
    char str[] = "Hello, C Programming!";
    
    // strlen returns the count of characters excluding \0, which is 21
    int len = strlen(str); 
    
    printf("String length: %d\n", len); 
    return 0;
}

strcpy: Safe String Copy Operations

When it is necessary to copy the content of a source string completely into another destination buffer, strcpy() is the preferred solution. This function copies the source string (including the trailing \0) character by character to the target address. The key point is that the capacity of the destination buffer must be strictly greater than or equal to the length of the source string plus one; otherwise, it leads to severe memory overflow vulnerabilities.

Unlike memcpy, which operates on raw byte sequences, strcpy is specifically designed for copying C-style strings terminated by \0. Therefore, it automatically handles the copying of the terminator, ensuring the validity of the target string. The following code demonstrates the basic copy process:

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

int main() {
    char src[] = "C is powerful";
    // dst must accommodate at least src length (16) + 1 (\0), i.e., 17 bytes
    char dst[20]; 
    
    strcpy(dst, src);
    
    printf("Copy result: %s\n", dst); 
    return 0;
}

strcat: String Concatenation and Memory Management Challenges

strcat() is used to append a source string to the end of a target string. The function first locates the current termination position of the target string and then copies the content of the source string (including \0) from that position onwards. This process imposes higher safety requirements on programmers: if insufficient space is reserved, buffer overflow is highly likely.

Similar to strcpy, when using strcat, it is mandatory to ensure the total capacity of the target array exceeds "original length + new string length". The following example demonstrates how to correctly concatenate two text segments:

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

int main() {
    char prefix[] = "Welcome to ";
    char suffix[] = "the world of C.";
    // Total capacity must cover prefix (13) + suffix (20) + \0, approximately 34 bytes
    char buffer[50]; 
    
    strcat(buffer, prefix);
    strcat(buffer, suffix);
    
    printf("Concatenation result: %s\n", buffer); 
    return 0;
}

Best Practices and Security Tips

Although strlen, strcpy, and strcat are powerful, their usage in modern C programming requires extreme caution. Since these functions do not check the size limits of the destination buffer, if input data exceeds the expected range, it compromises the integrity of heap memory, potentially causing program crashes or allowing malicious execution of arbitrary code (i.e., the famous "format string vulnerability" or buffer overflow attacks).

To enhance code security, the following principles are recommended:

  1. Always verify capacity: Before using strcpy and strcat, you must calculate and confirm that the destination array has sufficient space.
  2. Consider alternative solutions: When dealing with user input, prioritize safer functions such as snprintf, strncpy (requiring manual control of copy length), or size-limited variants introduced in the C99 standard (if supported by your compiler).
  3. Avoid risks from chained operations: When performing multiple string concatenations, calculate the required total space in advance and allocate memory in a single operation, rather than repeatedly calling realloc within a loop.

Mastering the principles and usage of these three functions is an essential path for every C language developer moving from beginner to expert level. They not only reflect the low-level characteristics of the language but also deeply illustrate the opportunities and challenges brought by manual resource management.