「工欲善其事,必先利其器。」C 語言標準庫 (libc, 嵌入式常用 uClibc/musl) 是系統編程的基石。熟練掌握常用庫函數,能避免重複造輪子、減少 Bug、提升代碼可移植性。本文按頭文件分類匯總高頻函數,並給出**工程落地建議**。
strncpy 不補 '\0', sprintf 返回值) 可能不同,**關鍵路徑必須實測**。man 3 <func> (Linux), cppreference.com, 《C標準庫》 (P.J. Plauger), 《UNIX環境高級編程》(APUE) — **職業生涯第一參考書**。int, 行為受 locale 影響)| 函數 | 用途 | 備註 |
|---|---|---|
isalpha, isdigit, isalnum | 判斷字母/數字/字母數字 | 僅對 ASCII 0-127 保證行為一致 |
islower, isupper | 判斷大小寫 | |
isspace | 判斷空白字符 (空格,\t,\n,\v,\f,\r) | |
tolower, toupper | 大小寫轉換 | 非字母原樣返回 |
⚠️ 坑:參數必須是 unsigned char 轉 int 或 EOF,否則負值 (如 char 有符號時) 導致未定義行為。正確用法:isalpha((unsigned char)ch)。
| 類別 | 函數 | 關鍵語義 / 易錯點 |
|---|---|---|
| 複製/拼接 | strcpy, strncpy | strncpy **不保證** 以 '\0' 結尾!需手動補。推薦 strlcpy (BSD) / strcpy_s (C11) |
strcat, strncat | 同樣有緩衝區溢出風險,需計算剩餘空間 | |
memcpy, memmove | 首選 處理二進制數據/重疊內存。memmove 安全處理重疊 | |
memset | 按字節填充。**不可用於初始化非 0 的 int/float 數組** | |
| 比較/查找 | strcmp, strncmp | 返回 <0, 0, >0。strncmp 比較前 n 字符 |
strchr, strrchr | 查找字符首次/末次出現位置,返回指針 | |
strstr | 查找子串 (KMP/BMH 實現),返回指針 | |
| 長度/轉換 | strlen | 不含 '\0'。O(n),循環中勿重複調用 |
printf/scanf 族。格式化字符串漏洞:printf(user_input) 致命!永遠用 printf("%s", user_input)。fopen/fclose/fread/fwrite/fseek/ftell/fflush。注意 fread 返回「成功讀取項數」而非字節數。setvbuf 設置行緩衝/全緩衝/無緩衝。fflush(stdout) 強制刷新 (交互式程序關鍵)。tmpfile() (自動刪除), tmpnam() (不安全)。| 領域 | 關鍵函數 | 核心提示 |
|---|---|---|
| 動態內存 | malloc, calloc, realloc, free, aligned_alloc (C11) | calloc 零初始化且檢查溢出。free 後指針置 NULL。檢查返回值! |
| 字符串轉數值 | strtol, strtod, strtoul 族 | 唯一正規解析方式**,支持錯誤檢查 (endptr)、基數、溢出檢測 (errno=ERANGE)。棄用 atoi/atof |
| 隨機數 | rand, srand (弱) / random, srandom / getrandom (Linux) | 加密用途必須用 /dev/urandom 或 BCryptGenRandom (Win) |
| 程序控制 | exit, _exit, atexit, abort, system | _exit 不刷新流/調用 atexit。system 有注入風險 |
| 環境變量 | getenv, setenv, unsetenv, putenv | |
| 排序/查找 | qsort, bsearch | 泛型接口,需編寫比較函數 int (*cmp)(const void*, const void*) |