Strings & <string.h>

Strings & <string.h> in C: Most languages hand you a string object that knows its own length.

The Analogy: A Sentence on a Ribbon, With a Knot at the End

Most languages hand you a string object that knows its own length. C hands you a ribbon of characters with a knot tied at the end, and nothing else.

The knot is the byte '\0' — the null terminator. It is not decoration; it is the only record of where the text stops. To find the length, C walks the ribbon from the start counting characters until it reaches the knot, every single time you ask. To copy the text somewhere, you must first know that the destination ribbon is long enough, because nothing will stop the copy once it starts.

Two consequences follow, and between them they account for a large share of the security bugs in the history of software. Cutting the knot off — overwriting the terminator, or forgetting to leave room for it — means every later read runs off the end of your text into unrelated memory. And copying a long ribbon into a short one does not fail; it simply keeps writing past the end, over whatever was there.


Syntax or Core Structure

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

int main(void) {
    char greeting[] = "hello";      /* 6 bytes: h e l l o and the terminator */
    char buffer[16];

    printf("greeting = [%s]\n", greeting);
    printf("strlen   = %zu\n", strlen(greeting));
    printf("sizeof   = %zu\n", sizeof greeting);

    strcpy(buffer, greeting);       /* buffer must be big enough -- it is */
    strcat(buffer, ", world");
    printf("buffer   = [%s] (len %zu)\n", buffer, strlen(buffer));

    printf("hello vs hello  = %d\n", strcmp("hello", "hello"));
    printf("apple before banana? %d\n", strcmp("apple", "banana") < 0);
    return 0;
}

Output:

greeting = [hello]
strlen   = 5
sizeof   = 6
buffer   = [hello, world] (len 12)
hello vs hello  = 0
apple before banana? 1

strlen says 5 and sizeof says 6, and that one-byte gap is the terminator. Internalise it now: a string of N characters needs N + 1 bytes. Every buffer-size calculation in C includes that + 1, and the ones that forget it are the ones that break.

Note also that strcmp returns 0 for equal — it reports an ordering, not a boolean, so the idiomatic equality test is strcmp(a, b) == 0, which reads backwards until you get used to it.

The functions worth knowing

FunctionDoesWatch out for
strlen(s)counts up to the terminatorO(n); never call it in a loop condition
strcpy(d, s)copies s into dno bound at all; the classic overflow
strncpy(d, s, n)copies at most n bytesdoes not terminate if s is that long
strcat(d, s)appends s to dunbounded, and rescans d to find its end
strcmp(a, b)orders two strings0 means equal
strncmp(a, b, n)compares the first n bytesthe right tool for prefix tests
strchr(s, c)finds a characterreturns NULL when absent
strstr(s, sub)finds a substringreturns NULL when absent
strtok(s, delims)splits in placemodifies s, keeps hidden state
memcpy(d, s, n)copies n bytesregions must not overlap; use memmove if they might
snprintf(d, n, fmt, ...)formats with a hard boundthe safe default for building strings

Technical Depth: Where Strings Actually Live

Two declarations that look almost identical produce completely different objects.

char  mutable_copy[] = "hello";     /* an array of 6 bytes, yours to modify */
const char *literal  = "hello";     /* a pointer to read-only program data  */

mutable_copy[0] = 'H';              /* fine: "Hello" */
/* literal[0] = 'H';                   undefined behaviour -- often a crash */

The array form copies the six bytes into your variable at initialisation. The pointer form points into the literal itself, which the compiler typically places in a read-only section of the executable. Writing there is undefined behaviour and, on most modern systems, a segmentation fault — one of the few C bugs that fails loudly, which is a mercy.

Always write const char * for a pointer to a literal. The const turns a runtime crash into a compile error.

sizeof versus strlen

ExpressionOn char buf[16] = "hi";On const char *p = "hi";Inside void f(char *s)
sizeof16 — the capacity8 — the pointer8 — the pointer, never the buffer
strlen2 — the content2 — the content2 — the content

The third column is the trap. A function that receives a char * cannot discover the buffer's capacity; sizeof s gives the pointer size. Capacity must be passed as a separate argument, exactly as with any other array.

The safe way to build a string

strcpy and strcat take no size and will happily write past the end of a buffer. strncpy looks like the fix but is not: if the source is at least n bytes long it copies n bytes and leaves no terminator, and if the source is shorter it pads the rest of the buffer with zeros. Neither behaviour is what anybody wants.

snprintf is the tool. It always terminates, it never exceeds the size you give it, and its return value tells you whether it had to truncate:

char out[16];
int n = snprintf(out, sizeof out, "%s-%d", "order", 4517);

if (n < 0) {
    /* encoding error */
} else if ((size_t)n >= sizeof out) {
    /* n is the length it WANTED to write, so the result was truncated */
}

That return-value contract is the part people miss: snprintf returns the length the full result would have been, not the number of bytes written. So n >= sizeof out is the truncation test, and n itself tells you exactly how big the buffer needed to be.

strlen in a loop condition is quadratic

for (size_t i = 0; i < strlen(s); i++) { ... }     /* rescans the whole string every step */

size_t len = strlen(s);                            /* once */
for (size_t i = 0; i < len; i++) { ... }

The first loop walks the string once per character, so a 100,000-character string performs about five billion byte comparisons. Compilers sometimes hoist the call, but only when they can prove the string is unmodified — do not rely on it.

Comparing with == compares addresses

const char *a = "hello";
char b[] = "hello";

a == b                  /* false: two different addresses */
strcmp(a, b) == 0       /* true: the same characters */

Confusingly, "hello" == "hello" in one translation unit may well be true, because the compiler is allowed to store identical literals once. That accidental success is why the bug survives a first test.


Real World Example: Labels That Cannot Overflow, and a Line Split Into Fields

Two jobs that appear in nearly every C program: compose a display string into a fixed buffer without overflowing it, and pull a delimited line apart into fields.

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

/* Returns 0 on success, -1 if the label did not fit.
   out is always a valid, terminated string either way. */
int make_label(char *out, size_t out_size, const char *first,
               const char *last, int id) {
    int want = snprintf(out, out_size, "%s %s (#%d)", first, last, id);
    if (want < 0) return -1;                       /* encoding failure */
    if ((size_t)want >= out_size) return -1;       /* truncated */
    return 0;
}

int main(void) {
    char label[32];
    if (make_label(label, sizeof label, "Ada", "Lovelace", 1815) == 0)
        printf("ok:        [%s]\n", label);

    char small[12];
    if (make_label(small, sizeof small, "Ada", "Lovelace", 1815) != 0)
        printf("truncated: [%s]\n", small);

    /* strtok writes terminators into its input, so never pass a literal.
       line is an array here, which makes it a writable copy. */
    char line[] = "203,widget,4.50,in-stock";
    const char *fields[8];
    size_t count = 0;

    for (char *tok = strtok(line, ","); tok != NULL && count < 8;
         tok = strtok(NULL, ","))
        fields[count++] = tok;

    for (size_t i = 0; i < count; i++)
        printf("field %zu:   [%s]\n", i, fields[i]);

    return 0;
}

Output:

ok:        [Ada Lovelace (#1815)]
truncated: [Ada Lovelac]
field 0:   [203]
field 1:   [widget]
field 2:   [4.50]
field 3:   [in-stock]

The full label is 20 characters, so it fits comfortably in 32. In the 12-byte buffer snprintf writes eleven characters plus the terminator and returns 20 — the length it wanted — which is how make_label knows to report failure. Crucially the short buffer still contains a properly terminated string, so the caller can print it safely even in the failure path. That combination, never overflow and always terminate, is what makes snprintf the right default.

The strtok loop is the shortest way to split a line, and it comes with three sharp edges worth knowing before you use it. It modifies its input, replacing each delimiter with '\0', so passing a string literal is undefined behaviour. It keeps hidden internal state between calls, so you cannot interleave two splits or call it from two threads. And it treats runs of delimiters as one, which means "203,,4.50" yields two fields rather than three — fatal for CSV, where an empty field is meaningful data.

For real delimited input, scan manually with strchr: find the next comma, terminate there, advance past it, and repeat. It is a dozen lines, it preserves empty fields, and it has no hidden state.


Common Mistakes

  1. Forgetting the + 1. char buf[5]; strcpy(buf, "hello"); needs six bytes and writes six. The text fits and the terminator does not, which is enough to corrupt the next variable.
  1. Using strcpy or strcat on untrusted input. Neither takes a size. If the source can be longer than the destination — and input from a file, a socket or a user always can — the write runs past the end.
  1. Modifying a string literal. char *s = "hello"; s[0] = 'H'; is undefined behaviour. Declare it const char *, or copy into an array with char s[] = "hello";.
  1. Comparing strings with ==. It compares addresses. It will occasionally be true by accident for identical literals, which makes the bug intermittent. Use strcmp(a, b) == 0.
  1. Trusting strncpy to terminate. If the source is at least n bytes, the destination has no terminator and the next printf walks off the end. Either terminate by hand afterwards or use snprintf.
  1. Calling strlen in a loop condition. Quadratic behaviour that looks like ordinary code. Hoist it into a variable.
  1. Using sizeof on a char * parameter to get the capacity. It yields the pointer size, typically 8, regardless of the buffer behind it. Pass the capacity explicitly.
  1. Ignoring snprintf's return value. Silent truncation produces a plausible-looking short string — a filename missing its extension, an id missing its last digits — and no error anywhere.

Best Practices

  • Make snprintf your default for building any string. Check the return value against the buffer size every time.
  • Pass capacity alongside the pointer: char *out, size_t out_size. Use sizeof buf at the call site, where the array is still an array.
  • Declare every pointer to text you do not intend to modify as const char *.
  • Size buffers from a named constant that includes the terminator, and comment the reasoning: char name[MAX_NAME + 1];.
  • Call strlen once and store the result.
  • Use strncmp(s, prefix, strlen(prefix)) == 0 for prefix tests rather than copying substrings out.
  • Prefer memmove over memcpy whenever the source and destination could overlap, such as shifting characters within one buffer.
  • Avoid strtok in anything reusable. Its hidden state makes the function that uses it non-reentrant, which is a property that spreads to every caller.

Practice Exercises

  1. Measure the knot. For char a[] = "syntax";, const char *b = "syntax"; and char c[16] = "syntax";, print strlen and sizeof for each and explain all six numbers in one sentence apiece. Then write a[6] = '!'; — overwriting the terminator — print a and strlen(a), and describe what you observe and why it varies between runs.
  1. Break it, then fix it. Write a program that copies a 20-character string into char small[8] with strcpy, with an int sentinel = 12345; declared immediately after. Print sentinel before and after. Rebuild with -fsanitize=address -g and record the report. Then rewrite the copy with snprintf so that it truncates safely and reports that it did.
  1. A safe append helper. Implement int append(char *dst, size_t dst_size, const char *src) that appends src to dst, never writes past dst_size, always leaves dst terminated, and returns 0 on success or -1 on truncation. Test it by appending three words into a 16-byte buffer and confirm the exact point at which it starts refusing.
  1. A CSV splitter that keeps empty fields. Using only strchr and pointer arithmetic, split "203,,4.50,,in-stock" into five fields and print each in brackets so the empty ones are visible. Then split the same data with strtok, print the result, and state how many fields each approach produced.
  1. A word counter. Read a line with fgets into a 256-byte buffer, strip the trailing newline, then report the character count, the word count (runs of non-space characters), and the longest word. Handle leading, trailing and repeated spaces correctly, and confirm that an empty line reports zero words rather than one.