← 返回课程: C programming from scratch

string.h and its dangers, and week 4 review

视频即将上线

The <string.h> header gathers the functions to manipulate strings and blocks of memory. They are fast and useful, but several were designed in an age when security was not a concern, and using them carelessly causes buffer overflows. In this lesson you will learn what each does, why some are dangerous and how to use them safely.

The essential functions

  • strlen(s): length without counting the terminator (it walks the string, so it is O(n))
  • strcmp(a, b): compares; returns 0 if equal, negative or positive according to order
  • strncmp(a, b, n): compares only the first n characters
  • strcpy(dst, src): copies without checking size (dangerous)
  • strcat(dst, src): concatenates without checking size (dangerous)
  • strchr and strstr: search for a character or a substring
  • memcpy, memmove, memset: copy or fill blocks of bytes

A classic beginner mistake is comparing strings with ==. That compares memory addresses, not content, and almost always gives false. To know whether two texts are equal use strcmp(a, b) == 0. In the same way, you do not assign a string with =: an array cannot be assigned, it must be copied.

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

int main(void) {
    char a[] = "apple";
    char b[] = "apple";

    printf("a == b: %d\n", a == b);                 /* 0: different addresses */
    printf("strcmp == 0: %d\n", strcmp(a, b) == 0); /* 1: same content */
    printf("strcmp(\"apple\", \"banana\") < 0: %d\n",
           strcmp("apple", "banana") < 0);

    const char *found = strstr("learn C today", "C");
    if (found != NULL) {
        printf("found: %s\n", found);
    }
    return 0;
}

Why strcpy and strcat are dangerous

strcpy copies until it finds the terminator of the source, no matter how much space the destination has. If the source is longer, it writes beyond the array and corrupts neighboring memory. An attacker can exploit that overflow to take control of the program. The solution is to check the size before copying, or to use a function that takes the limit. strncpy looks like the solution, but it does not guarantee the terminator and pads with extra zeros, so it is often misused. A very practical, standard alternative is snprintf, which always respects the size and always terminates the string.

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

int main(void) {
    char dest[8];
    const char *source = "a very long text";

    /* strcpy(dest, source);   UNSAFE: 17 bytes into 8 */

    if (strlen(source) < sizeof(dest)) {
        strcpy(dest, source);              /* safe: size checked */
    } else {
        printf("too long, not copied\n");
    }

    int written = snprintf(dest, sizeof(dest), "%s", source);
    printf("dest = \"%s\" (would need %d chars)\n", dest, written);

    char path[32];
    snprintf(path, sizeof(path), "%s/%s", "docs", "notes.txt");
    printf("%s\n", path);
    return 0;
}

snprintf returns the length the complete result would have needed; if it is greater than or equal to the buffer size, the text was truncated. That way you can detect the truncation and decide what to do. To join strings, instead of strcat chain snprintf calls or compute the free space beforehand.

Week 4 review: you can declare and initialize arrays, walk them without going out of bounds, pass them to functions together with their length, represent text as char arrays ending in '\0', read lines with fgets and copy or compare strings safely. The final exercise combines everything and then you have the week quiz.

检验所学

第 1 / 6

If you declare int v[5], what is the last valid index?

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →