Skip to main content

Lesson 4 of 7

String Functions - The Complete Safety Guide

The `<string.h>` functions are fast but unforgiving - most unsafe variants (`strcpy`, `strcat`, `gets`) are classic sources of buffer overflows that have led to real security vulnerabilities (Heartbleed, Morris worm, etc.). Every C programmer must know the safe alternatives and understand **why** the unsafe versions are dangerous.

13 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

string.h - Safe vs Unsafe + All Important Functions

string.h - Safe vs Unsafe + All Important Functions
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
    char dst[16];
    const char *src = "Hello, World!";

    /* ── strlen - length WITHOUT the null terminator ────── */
    size_t len = strlen(src);   /* 13 */
    printf("strlen = %zu
", len);

    /* ── strcpy - UNSAFE if dst too small ───────────────── */
    /* strcpy(dst, src);  ← if src > sizeof(dst)-1: OVERFLOW */
    /* SAFE alternative: */
    strncpy(dst, src, sizeof(dst) - 1);
    dst[sizeof(dst) - 1] = '';   /* strncpy doesn't guarantee ! */
    printf("strncpy: %s
", dst);

    /* ── strcat - append (UNSAFE) ────────────────────────── */
    char result[32] = "Hello";
    /* strcat(result, ", World!!!!!!");  ← if too long: overflow */
    /* SAFE: check available space first: */
    const char *extra = ", C!";
    size_t avail = sizeof(result) - strlen(result) - 1;
    strncat(result, extra, avail);
    printf("strncat: %s
", result);

    /* ── strcmp & strncmp ────────────────────────────────── */
    printf("strcmp("abc","abd") = %d
", strcmp("abc","abd")); /* <0 */
    printf("strcmp("abc","abc") = %d
", strcmp("abc","abc")); /* 0 */
    printf("strcmp("abd","abc") = %d
", strcmp("abd","abc")); /* >0 */
    /* strncmp: compare at most n characters - use for prefixes */
    printf("strncmp 3 chars: %d
", strncmp("abcXXX","abcYYY",3)); /* 0 */

    /* ── strchr / strrchr - find a character ────────────── */
    const char *path = "/usr/local/bin/gcc";
    const char *last_slash = strrchr(path, '/');  /* last occurrence */
    if (last_slash) printf("filename: %s
", last_slash + 1);  /* gcc */

    /* ── strstr - find a substring ───────────────────────── */
    const char *haystack = "the quick brown fox";
    const char *needle   = strstr(haystack, "brown");
    if (needle) printf("found 'brown' at offset %td
", needle - haystack);

    /* ── strtok - split string by delimiter (DESTRUCTIVE) ── */
    char csv[] = "Alice,30,Engineer";   /* strtok MODIFIES the string! */
    char *token = strtok(csv, ",");
    while (token != NULL) {
        printf("token: %s
", token);
        token = strtok(NULL, ",");  /* NULL continues from last position */
    }

    /* ── memcpy / memmove / memset - raw memory ops ──────── */
    char buf[10];
    memset(buf, 0, sizeof(buf));   /* fill with zeros */
    memcpy(buf, "hi", 2);          /* copy 2 bytes - no null added! */
    buf[2] = '';
    printf("memcpy result: %s
", buf);

    /* memmove: safe when src and dst OVERLAP (memcpy is not safe) */
    memmove(buf + 1, buf, 2);   /* shift 2 bytes right by 1 */
    buf[3] = '';
    printf("memmove result: %s
", buf);

    return 0;
}

Common Mistakes

  • `strncpy` doesn't guarantee null-termination - if `src` is exactly `n` characters or longer, no `null terminator (\x00)` is written. Always: `strncpy(dst, src, n-1); dst[n-1] = '';`.
  • `strtok` modifies the input string and is not reentrant - never call `strtok` on a string literal or a string you don't own. On re-entry from a signal or second thread, it corrupts state. Use `strtok_r` on POSIX systems.
  • `gets()` is removed in C11 - `gets()` has no length limit and is the textbook buffer overflow function. Never use it. Prefer `fgets(buf, sizeof(buf), stdin)`.

Tip

Tip

Practice String Functions The Complete Safety Guide in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Always prefer bounded string functions (snprintf, strncpy) over unbounded counterparts

Practice Task

Note

Practice Task - (1) Write a working example of String Functions The Complete Safety Guide from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with String Functions The Complete Safety Guide is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • The `<string.
  • `strncpy` doesn't guarantee null-termination - if `src` is exactly `n` characters or longer, no `null terminator (\x00)` is written. Always: `strncpy(dst, src, n-1); dst[n-1] = '';`.
  • `strtok` modifies the input string and is not reentrant - never call `strtok` on a string literal or a string you don't own. On re-entry from a signal or second thread, it corrupts state. Use `strtok_r` on POSIX systems.
  • `gets()` is removed in C11 - `gets()` has no length limit and is the textbook buffer overflow function. Never use it. Prefer `fgets(buf, sizeof(buf), stdin)`.

Topics in This Module

0/7 done