忽略庫函式的返回值

幾乎 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;
}

通過這種方式,你可以立即知道錯誤原因,否則你可能需要花費數小時在完全錯誤的地方尋找錯誤。