忽略库函数的返回值

几乎 C 标准库中的每个函数都会在成功时返回一些内容,而其他函数则返回错误。例如,malloc 将返回指向函数在成功时分配的内存块的指针,如果函数未能分配所请求的内存块,则返回空指针。因此,你应该始终检查返回值以便于调试。

这是不好的:

char* x = malloc(100000000000UL * sizeof *x);
/* more code */
scanf("%s", x); /* This might invoke undefined behaviour and if lucky causes a segmentation violation, unless your system has a lot of memory */

这很好:

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
    char* x = malloc(100000000000UL * sizeof *x);
    if (x == NULL) {
        perror("malloc() failed");
        exit(EXIT_FAILURE);
    }

    if (scanf("%s", x) != 1) {
        fprintf(stderr, "could not read string\n");
        free(x);
        exit(EXIT_FAILURE);
    }

    /* Do stuff with x. */

    /* Clean up. */
    free(x);

    return EXIT_SUCCESS;
}

通过这种方式,你可以立即知道错误原因,否则你可能需要花费数小时在完全错误的地方寻找错误。