Curious Minds

Clear answers to science and history questions

C String Library Functions: Examples & Guide

· 7 min read · Science

The C standard library provides a set of string handling functions declared in <string.h> that let you copy, concatenate, compare, search, and measure null-terminated strings. These functions are the backbone of text processing in C, and understanding them—along with their pitfalls—is essential for writing safe and correct code.

What Are C String Library Functions?

In C, a string is not a built-in type; it is a sequence of characters stored in a char array and terminated by a null character ('\0'). The <string.h> header declares functions that operate on such strings. They are part of the C Standard Library, standardized by ISO/IEC 9899, and are available on virtually every C implementation.

These functions do not allocate memory (except strdup, which is POSIX, not standard C). They work on buffers you provide, which means you are responsible for ensuring the destination has enough space. This design gives C its characteristic performance but also its characteristic dangers.

Common categories include:

  • Copying and concatenation: strcpy, strncpy, strcat, strncat
  • Comparison: strcmp, strncmp, strcoll, strxfrm
  • Searching: strchr, strrchr, strstr, strpbrk, strspn, strcspn, strtok
  • Length and error: strlen, strerror
  • Memory (not string-specific but often used): memcpy, memmove, memset, memcmp

How the Core Functions Work (with Examples)

All string functions rely on the null terminator to know where the string ends. If the terminator is missing, they will read past the buffer, causing undefined behavior. Here are the most frequently used functions with concrete examples.

strlen

Returns the number of characters before the null terminator. It does not count the terminator itself.

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

int main(void) {
    const char *s = "hello";
    printf("%zu\n", strlen(s)); // prints 5
    return 0;
}

Note that strlen takes time proportional to the string length because it scans until it finds '\0'. Calling it repeatedly in a loop condition is a common performance mistake.

strcpy and strncpy

strcpy(dest, src) copies the string including the null terminator. strncpy(dest, src, n) copies at most n characters; if src is shorter than n, it pads dest with nulls up to n. If src is longer, dest may not be null-terminated.

char dest[10];
strcpy(dest, "cat"); // dest now holds "cat\0"
strncpy(dest, "elephant", 10); // no null terminator if src length >= 10

Because of this, many programmers prefer snprintf or manually setting the last byte to '\0' after strncpy.

strcat and strncat

strcat(dest, src) appends src to the end of dest, overwriting the null terminator and adding a new one. strncat(dest, src, n) appends at most n characters and always null-terminates (provided dest has room for the extra null).

char buf[20] = "Hello, ";
strcat(buf, "world!"); // buf becomes "Hello, world!"

Both require that dest is large enough to hold the result. Buffer overflows from misuse are a classic source of security vulnerabilities.

strcmp and strncmp

strcmp(a, b) compares two strings lexicographically (based on the character set's collating sequence, typically ASCII). It returns a negative value if a < b, zero if equal, positive if a > b. strncmp compares only the first n characters.

if (strcmp(name, "admin") == 0) {
    // names are equal
}

Never compare strings with ==; that compares pointers, not contents.

strchr, strrchr, and strstr

strchr(s, c) returns a pointer to the first occurrence of character c in s, or NULL if not found. strrchr finds the last occurrence. strstr(haystack, needle) returns a pointer to the first occurrence of the substring needle in haystack.

const char *text = "user@example.com";
const char *at = strchr(text, '@');
if (at) printf("Domain: %s\n", at + 1); // prints "example.com"

strtok

strtok splits a string into tokens using a set of delimiters. It modifies the original string by inserting null bytes and maintains internal state, so it is not reentrant or thread-safe. strtok_r (POSIX) is the reentrant version.

char str[] = "apple,banana,cherry";
char *token = strtok(str, ",");
while (token) {
    printf("%s\n", token);
    token = strtok(NULL, ",");
}

How to Choose the Right Function

Selecting the correct function depends on what you need to do and how much control you have over buffer sizes. Consider these guidelines:

  • Copying: Use strcpy only when the destination is guaranteed large enough. Prefer snprintf or strncpy with explicit null termination for safer bounded copies.
  • Concatenation: strcat is simple but unsafe if sizes are uncertain. strncat limits the number of characters appended but still requires enough space in the destination.
  • Comparison: Use strcmp for full equality or ordering; strncmp when comparing prefixes.
  • Searching: strchr for single characters, strstr for substrings. For multiple delimiters, strpbrk or strtok.
  • Tokenizing: strtok is convenient but destructive and non-reentrant; use strtok_r in multithreaded code.

Always check return values (especially for NULL) and ensure buffers are large enough. When in doubt, use bounded functions and validate lengths.

Common Problems and Safety Considerations

Misuse of string functions is a leading cause of bugs and security holes in C programs. Here are the most frequent issues:

  • Buffer overflow: strcpy and strcat do not check destination size. If the source is longer than the destination, memory is corrupted.
  • Missing null terminator: strncpy may not null-terminate if the source length equals or exceeds n. Always set dest[n-1] = '\0' or use a safer alternative.
  • Off-by-one errors: Forgetting space for the null terminator when allocating buffers.
  • Modifying string literals: String literals are typically stored in read-only memory. Passing a literal to strtok or modifying it directly causes undefined behavior.
  • Using strcmp result incorrectly: The return value is not guaranteed to be -1, 0, or 1; it can be any negative, zero, or positive value.
  • Thread safety: Functions like strtok use static internal state and are not thread-safe. Use reentrant versions where available.

To mitigate these risks, consider using bounds-checked alternatives from Annex K (like strcpy_s) where supported, or platform-specific safe string libraries. However, Annex K is not universally implemented, so portable code often relies on careful manual checks or third-party libraries.

Alternatives and Extensions

Beyond the standard C library, several alternatives exist:

  • POSIX functions: strdup (duplicates a string), strndup, strtok_r, strcasecmp (case-insensitive compare).
  • Annex K (C11): Bounds-checked functions like strcpy_s, strcat_s, strncpy_s. These are optional and not widely available.
  • Third-party libraries: Safe string libraries (e.g., SafeStr, strlcpy/strlcat from BSD) provide bounded copying with guaranteed null termination. strlcpy and strlcat are available on many systems but not standardized in ISO C.
  • C++ strings: If using C++, std::string manages memory automatically and avoids many pitfalls.

When portability is paramount, sticking to standard C functions with rigorous size checks is often the most reliable approach.

Frequently Asked Questions

Why does strcmp return values other than -1, 0, and 1?

The C standard only specifies the sign of the return value: negative if the first string is less, zero if equal, positive if greater. Implementations may return the difference between the first differing characters, which can be any integer. Always compare the result to zero rather than to specific values.

Is strncpy safer than strcpy?

strncpy limits the number of characters copied, which can prevent some overflows, but it does not guarantee null termination if the source is too long. It also pads with nulls if the source is short, which can be inefficient. For safe copying, many developers prefer snprintf or manually ensuring termination.

Can I use strtok on a string literal?

No. strtok modifies the string it processes by inserting null bytes. String literals are typically stored in read-only memory, so attempting to modify them causes undefined behavior, often a crash. Always pass a modifiable character array.

What is the difference between strchr and strrchr?

strchr returns a pointer to the first occurrence of a character in a string, while strrchr returns a pointer to the last occurrence. Both return NULL if the character is not found.

How do I compare strings ignoring case?

Standard C does not provide a case-insensitive comparison function. POSIX defines strcasecmp and strncasecmp, which are available on many systems. Alternatively, you can convert both strings to a common case using tolower from <ctype.h> and then use strcmp.

Why does strlen take O(n) time?

strlen must scan the string from the beginning until it finds the null terminator, so its running time is proportional to the string length. There is no stored length in C strings, unlike in many higher-level languages.

In this article
  1. What Are C String Library Functions?
  2. How the Core Functions Work (with Examples)
  3. How to Choose the Right Function
  4. Common Problems and Safety Considerations
  5. Alternatives and Extensions
  6. Frequently Asked Questions