CThe string.h Library

The string.h Library

C's standard library ships a dedicated header, <string.h>, packed with functions for working with null-terminated strings: measuring length, copying, concatenating, comparing, and searching. Because C strings are just char arrays with a convention (see Strings as Char Arrays), all of these functions operate by scanning memory for a '\0' byte — which is exactly why several of them are dangerous if you are not careful about buffer sizes.
Including the Header

C
#include <string.h>
Key Functions at a Glance

Function

What it does

strlen(s)

Returns the number of characters in s, not counting the null terminator

strcpy(dest, src)

Copies src into dest, including the terminator -- no bounds checking

strncpy(dest, src, n)

Copies at most n characters from src into dest -- bounded, but may not null-terminate

strcat(dest, src)

Appends src onto the end of dest -- no bounds checking

strncat(dest, src, n)

Appends at most n characters from src onto dest, and always null-terminates

strcmp(a, b)

Compares two strings lexicographically; returns 0 if equal, negative if a < b, positive if a > b

strncmp(a, b, n)

Like strcmp, but compares at most the first n characters

strchr(s, c)

Returns a pointer to the first occurrence of character c in s, or NULL if not found

strstr(haystack, needle)

Returns a pointer to the first occurrence of substring needle in haystack, or NULL

strtok(s, delim)

Splits s into tokens separated by any character in delim; modifies s and keeps internal state

Bounds Checking Is Mostly Your Job
Several classic string.h functions have no bounds checking
Functions like strcpy and strcat will happily write past the end of a destination buffer if the source content doesn't fit — they have no way to know how big dest actually is. This has made them the source of countless real-world security vulnerabilities over the decades. Bounded variants like strncpy and strncat exist to limit how much gets written, but they come with their own subtleties — for example, strncpy does not guarantee the result is null-terminated if the source is too long. Bounded does not automatically mean safe; you still need to understand exactly what each function guarantees. The next page walks through worked examples of these functions and their pitfalls in detail.
  • <string.h> provides functions for length, copying, concatenation, comparison, and searching on C strings

  • All of these functions work by scanning for a null terminator, just like printf("%s", ...)

  • strcpy and strcat have no bounds checking -- classic sources of buffer overflows

  • The bounded n-variants (strncpy, strncat, strncmp) limit how much is read or written, but still require care

  • Understanding what each function actually guarantees (especially around null-termination) matters more than just picking the "safe-sounding" version